- Home /
How can I instantiate a unique game object?
Title says it all, I am working on a project that includes an enemy spawner on a timer. Every 15 seconds a new one should spawn. It does this but when a clone is spawned, the original becomes invulnerable and also deals no damage, the same follows with all the clones.
Is there a way to instantiate a completely unique game object with the health values etc completely specific to that one object?
Here's the code for the enemy spawner: public class RobotSpawner : MonoBehaviour { public float SpawnDelay; public float SpawnDelayMax = 15f; public GameObject Robot; public Transform Spawner;
private void FixedUpdate()
{
SpawnDelay += Time.deltaTime;
if(SpawnDelay >= SpawnDelayMax)
{
SpawnDelay = 0;
Instantiate(Robot, Spawner);
}
}
}
Am I being dumb, is this possible?
Answer by Twinklier · Dec 29, 2019 at 07:35 AM
What do you mean unique? Like having that entity have random health and whatnot? if so use Random.Range(min, max). So right at the spawning of that entity you change its health and whatnot to a random number.
also Time.deltaTime and Time.fixedDeltaTime has different values. And try not to use FixedUpdate in situation like this. It's better for your computer's health if you reserve that for physics calculations instead.
Answer by LOSTSOUL86 · Dec 29, 2019 at 10:04 AM
@LukeThePunk666 Yes it is possible. You just need to save "new" object as a prefab. Just create game object - Robot and drag it from the Hierarchy to the Resources folder) then it becomes a prefab then in the code you need to load it:
prefabRobot = Resources.Load("Robot") as GameObject;
if (prefabRobot == null)
{
Debug.LogError("Didn't find Robot");
}
And then instantiate it always from this game object
newRobot = Instantiate(prefabRobot) as GameObject;
Dont use prefabRobot gameobject in your game - it is just new object from which you always take copy copy.
You can also attach script to Robot that will set all values for you. It will be executed with each robot at the begining.
A prefab is like an original form where you look for to make a copy. It's created and stored in the asset folder. (Although Instantiate() doesn't always need prefabs, it would be a lot cleaner to do it this way)
Your answer
Follow this Question
Related Questions
How to spawn objects using an array of spawn points w/o intersecting 1 Answer
When the game starts, how can I instantiate a ball onto a random client? 0 Answers
Instantiated Bullets Not Picking Up Correct Position/Rotation 2 Answers
instantiate objects from right and left of screen to center 0 Answers
Why is it important to create an empty gameobject for my prefabs? 0 Answers