首页 > 解决方案 > 我的统一预制件在一个接一个生成时没有运行脚本(使用 XR 控制器)

问题描述

与这里的大多数人类似,我对统一场景相当陌生,我正在尝试在我的游戏中创建一个特定的机制:我想创建一个灌木丛,我可以从中生成水果物品;灌木上的果实需要特定的时间才能生长,并且在它们完全长大之前不能与之相互作用。一旦你抓住水果,它就会在原来的位置产生另一个以重复循环。

然而,代码的工作原理是它产生第一个水果,一旦长大就会生长并相互作用,但是一旦我抓住第一个水果,植物就会停止生长并只显示完全成长的对象(但是每次你抓住那个水果后它会产生另一个水果正如预期的那样),该对象不会与重力发生反应,这与在交互后应用重力的原始对象不同。

该对象是一个预制件,包含以下脚本:



using System.Collections; using System.Collections.Generic;

using UnityEngine; using UnityEngine.XR.Interaction.Toolkit;

public class GrowthScript : MonoBehaviour { Collider ObjectCol; [SerializeField] private GameObject Item;

 public int GrowTime = 6;
 public float MinSize = 0.1f;
 public float MaxSize = 1f;
 public float Timer = 0f;
 private XRGrabInteractable grabInteractable = null;
 
 public bool IsMaxSize = false;
 public bool CanRegrow = false;
 // Start is called before the first frame update
 void Start()
 {
     Debug.Log("Growing");
     IsMaxSize = false;
     ObjectCol = GetComponent<Collider>();
     // if the plant isnt full size, it starts a routine to grow
     if (IsMaxSize == false)
     {
         ObjectCol.enabled = !ObjectCol.enabled;
         StartCoroutine(Grow());
     }
 }
 private void Awake()
 {
     grabInteractable = GetComponent<XRGrabInteractable>();
     grabInteractable.onSelectEntered.AddListener(Obtain);
     
 }
 private IEnumerator Grow()
 {
     Vector3 startScale = new Vector3(MinSize, MinSize, MinSize);
     Vector3 maxScale = new Vector3(MaxSize, MaxSize, MaxSize);
     do
     {
         transform.localScale = Vector3.Lerp(startScale, maxScale, Timer / GrowTime);
         Timer += Time.deltaTime;
         yield return null;
     }
     while (Timer < GrowTime);
     IsMaxSize = true;
     CanRegrow = true;
     Debug.Log("Grown");
     ObjectCol.enabled = !ObjectCol.enabled;
 }
 private void Obtain(XRBaseInteractor interactor)
 {
     if (CanRegrow == true)
     {
         
         GameObject instance = Instantiate(Item, transform.position, transform.rotation) as GameObject;
         CanRegrow = false;
     }
 }
}

如果我能得到关于为什么预制件在重生时不运行代码或解决问题的方法的帮助,我将不胜感激。

非常感谢(祝你好运)

标签: c#unity3d

解决方案


推荐阅读