GameObject wont correctly instantiate into an array
I'm trying to make a script for a chain, which spawns a certain amount of chain links based on a variable in the inspector. I can not figure out why my code will not instantiate more than one link. I have verified that my loop runs the correct number of times when I remove the instantiate line. Here is my code:
private void Start()
{
for (int numOfChainsToSpawn = 0; numOfChainsToSpawn != numOfChains; numOfChainsToSpawn++)
{
chains[numOfChainsToSpawn] = Instantiate(chainLink, transform.position, transform.rotation);
}
}
Every time I run the Project, it instantiates one link, then I get a nullReference exception. Any ideas on what could be causing this?
Are you sure that error is related to this specific part of your code? I would assume that your link object has as script component with empty reference. And when in Instantiates, it tries to use it somehow?
This is the only piece of code, besides initializing variables. Also, the link object is just a sprite renderer and a hinge joint, no connected scripts. Its really strange that this happens, especially since It does spawn the first one, but none of the others
Answer by Reid_Taylor · May 03, 2021 at 03:17 PM
Well I see 2 problems. First of all the array needs to be created... At this point the array has no length so when you try to access the array[2], it doesn't exist yet. Second of all you should use < not != in a for loop(kinda personal preference)
private void Start()
{
chains = new "Whatever type chain is"[numOfChains];
for (int i = 0; i < chains.Length; i++)
{
chains[i] = Instantiate(chainLink, transform.position, transform.rotation);
}
}
Your answer
Follow this Question
Related Questions
Instantiating object randomly withing the boundaries of an object. 0 Answers
Add Component with Script Data 1 Answer
RPG instantiate problem 3 Answers
Instantiate() and Destroy() vs setActive() 1 Answer
Destroying game object 0 Answers