How to pass a game object through to a function?
I am looking to create a general script that will spawn the game object passed to it within the play area as required. However I am receiving the error that "'spawn' takes 0 arguments". The GameObjects are all declared at the top of the script, (e.g. public GameObject food;) and I am sending them to this function with a line like this in the update section:
if (GlobalVars.foodToSpawn > 0 )
{
spawn(food);
GlobalVars.foodToSpawn -= 1;
print ("Food to spawn: " + GlobalVars.foodToSpawn);
}
Below, the spawn function looks like this:
void spawn(GameObject thing)
{
float x = Random.Range (playAreaMinX, playAreaMaxX);
float z = Random.Range (playAreaMinZ, playAreaMaxZ);
Instantiate(thing, new Vector3 (x, 0, z), transform.rotation);
}
This is presumably the wrong way to send a game object to a function as a variable, but I don't know why.
Everything looks fine, is the spawn
function declared inside the same script? Have you any other spawn
without any argument or a variable called spawn
?
Answer by Matti-Jokipii · Feb 06, 2018 at 10:56 PM
Clearly your function declaration and call is correct. There must be another spawn() function in the scope, that gets called. Try changing the name to spawn2 or something. If that helps, figure out why the wrong spawn is in the scope.
Answer by NEOpera · Feb 07, 2018 at 02:30 PM
For future reference I ended up using the function just to get the random variables, and then instantiating using that variable. As a result I don't know if it would have helped to change the name of the function.
Your answer
Follow this Question
Related Questions
Variables and Functions {Tutorial Question} 1 Answer
Multiple variables in a function? Like function test (number : float , number1 : float) 0 Answers
Passing variable name into function from different script/animation event editor 0 Answers
How to run a function without certain input variables? 0 Answers
How can you add a function to a variable. Such as string.ToUpper() ? 1 Answer