- Home /
Set a variable in another object at point of instantiation.
I'm making a whack-a-mole game and when a timer reaches 0 I call my Spawn() function. This does the following:
selects a random spawn point from a list.
removes that spawn point from the list temporarily.
creates a mole object at the spawn points position
finds a mole with tag "mole" in the scene
sets the spawnpoint variable of that mole to whichever point was removed from the list.
This all works fine whilst I'm using one "mole." However, when spawning more than one in the scene at once, point 4 above is giving me problems. using FindWithTag just finds any mole object in the scene, which sometimes passes rsp to the wrong mole.
Is there a way to set the mySpawnPoint of the mole at the point it is instantiated, rather than use FindWIthTag?
If any additional code is useful, please let me know.
Thank you.
My code for the function is below:
function Spawn()
{
rsp = SpawnPointList[Random.Range(0,SpawnPointList.Count)]; //rsp = random spawn point picked from the list
SpawnPointList.Remove(rsp); // remove the selected spawn point from the list, preventing it from being selected again whilst mole is there
//Debug.Log("the spawn point removed from the list is: " + rsp);
Instantiate(mole,rsp.transform.position,rsp.transform.rotation); //create mole at rsp
var mole = GameObject.FindWithTag("mole").transform; //find and use mole in the scene
var script: MoleScript = mole.GetComponent(MoleScript); //assign script to the moles moleScript
script.mySpawnPoint = rsp; //access the "myspawnpoint" variable inside the mole
}
Answer by Spider_newgent · May 20, 2015 at 12:48 PM
Okay, so I figured this one out myself.
For anyone else who encounters the same problem, instead of using FindWIthTag, just declare "mole" at the point of instantiation, rather than instatiating it and setting the value of "mole" afterwards. I've posted the amended spawn function below:
function Spawn()
{
rsp = SpawnPointList[Random.Range(0,SpawnPointList.Count)]; //rsp = random spawn point picked from the list
SpawnPointList.Remove(rsp); // remove the selected spawn point from the list, preventing it from being selected again whilst mole is there
var mole:Transform = Instantiate(mole,rsp.transform.position,rsp.transform.rotation); //THIS IS THE CHANGED LINE.
var script: MoleScript = mole.GetComponent(MoleScript); //assign script to the moles moleScript
script.mySpawnPoint = rsp; //access the "myspawnpoint" variable inside the mole
}
Your answer
Follow this Question
Related Questions
Variable of prefab has not been assigned 2 Answers
Getting a component of an instantiated object returns an error 1 Answer
How do I acces a specific GameObject within the terrain???? 1 Answer
Instantiate Prefabs. Errors. 2 Answers
Only change a variable on the instaniated object not the prefab. 0 Answers