Skip to content Skip to sidebar Skip to footer

Spawning Game Object Unity (c#)

I writing simple runner game. I have game object (quad). I want it to generate. I wrote spawnscript: using UnityEngine; using System.Collections; public class SpawnScript : Mo

Solution 1:

Use InvokeRepeating instead of Invoke in start event:

// Invokes the method methodName in time seconds, then repeatedly every   repeatRate seconds.
InvokeRepeating("Spawn", 3, 3);

If you do InvokeRepeating("Function", 1.0f, 1.0f), it will call Function one second after the InvokeRepeating call and then every one second thereafter. Hence, you can control the spawn timings.

Update

As asked in comments:

You can also cancel InvokeRepeating any time by calling below code. More information here.

CancelInvoke("Spawn");

Solution 2:

There is no problem with code. All GameObjects instantiated same position so you can use code below:

publicfloat spawnDistanceFactor = 2f; //Value is your choice. You can change it.voidSpawn() 
{ 
     float startPosX = 0f; // I assume your camera look at 0,0,0 point.for (int i = 0; i < 10; i++){ 
         Vector3 spawnPos = new Vector3(startPosX,0f,0f);
         Instantiate(obj, spawnPos, Quaternion.identity); 
         startPosX+=spawnDistanceFactor;
     }

} 

It is only moves positions on X axis you can move it x,y,z.

Also

You can use Random function for moving spawn position

publicfloat randomMin = 2f;
publicfloat randomMax = 4f;
voidSpawn() 
{ 
     float startPosX = 0f; // I assume your camera look at 0,0,0 point.for (int i = 0; i < 10; i++){ 
         Vector3 spawnPos = new Vector3(startPosX,0f,0f);
         Instantiate(obj, spawnPos, Quaternion.identity); 
         float randomX = Random.Range(randomMin,randomMax);
         startPosX+=randomX;
     }

} 

You can do a lot of things.

For destroying prefabs you can add Destroy script to object (You should create prefab with script) Like:

voidDestroyObject(){
     Destroy(this.gameObject);
} 

or use list to hold pointers to the GameObjects. Like:

using System.Collections.Generic;      // For listprivate List<GameObject> objectList;
publicfloat randomMin = 2f;
publicfloat randomMax = 4f;

voidStart(){
  objectList = new List<GameObject>();
  Spawn();
}
voidSpawn() 
{ 
     objectList.Clear();     ///For multiple spawn purpose dont dublicate items.float startPosX = 0f; // I assume your camera look at 0,0,0 point.for (int i = 0; i < 10; i++){ 
         Vector3 spawnPos = new Vector3(startPosX,0f,0f);
         GameObject newObject = Instantiate(obj, spawnPos, Quaternion.identity) as GameObject; 
         objectList.Add(newObject);
         float randomX = Random.Range(randomMin,randomMax);
         startPosX+=randomX;
     }
} 

voidDestroyObject(){
     for(int i=0;i<objectList.Count;i++){
         Destroy(objectList[i]);
     }
} 

Post a Comment for "Spawning Game Object Unity (c#)"