0

我早些时候实例化并销毁了我的游戏对象,但在得知它是处理器密集型的之后,我操纵了我的代码,使其成为一个包含 1 个对象的对象池。当我按下 Z 时,只要按下 Z,我的对象就会被激活并开始放大,并且在向上键时,它会停用对象,但是当再次按下 Z 时,对象不会再次被调用。我究竟做错了什么 ?

float speed = 2f;
public GameObject radius;
public int pooledAmount = 1;
List<GameObject> radiusorb;

void Start(){

   radiusorb = new List<GameObject> ();
   for (int i = 0; i < pooledAmount; i++)
   {
     GameObject obj = (GameObject)Instantiate (radius);
     obj.SetActive(false);
     radiusorb.Add (obj);
   }
}

void Update (){
   if(Input.GetKeyDown(KeyCode.Z))
   {
     Invoke("LetRadiusExist",0.001f);        //Instantiating the prefab
      }

   if (Input.GetKey(KeyCode.Z)) {              //Scale the object
     if (gameObject != null)
     {
      gameObject.transform.localScale += gameObject.transform.localScale * (Time.deltaTime * speed);
     }
   }

   if(Input.GetKeyUp(KeyCode.Z))               //To deactivate the prefab
   {
     gameObject.SetActive(false);

     //Destroy(cloneRadius, 0);
   }
}

void LetRadiusExist()
{
   for (int i = 0; i < radiusorb.Count; i++) 
   {
     if (!radiusorb[i].activeInHierarchy)
     {
      radiusorb[i].SetActive(true);
      radiusorb[i].transform.parent = transform;
      radiusorb[i].transform.localPosition = new Vector3(0,0,0);
      break;
     }

   }
}
4

1 回答 1

0

您正在更改您的实际游戏对象,而不是您汇集的半径对象。因此,当 Z 键被释放时,您将停用您的游戏对象,然后不会进行进一步的处理。

此外,您实际上不需要列表,因为您只使用一个对象。所以这可以简化很多:

float speed = 2f;
public GameObject radiusPrefab;

// your "pooled" instance.
private GameObject instance;

void Start(){
   instance = (GameObject)Instantiate (radiusPrefab);
   instance.SetActive(false);
}

void Update (){
   if(Input.GetKeyDown(KeyCode.Z))
   {
       instance.SetActive(true);
   }

   if (Input.GetKey(KeyCode.Z)) {              //Scale the object
      instance.transform.localScale += instance.transform.localScale * (Time.deltaTime * speed);
   }

   if(Input.GetKeyUp(KeyCode.Z))               //To deactivate the prefab
   {
      // make sure to reset the scale!
      instance.transform.localScale = Vector3.one;
      instance.SetActive(false);
   }
}
于 2014-04-10T11:44:53.573 回答