The question is answered, right answer was accepted
Why is the this object referenced to itself?
Hi!
I have this piece of code. It's choosing a random prefab out of a array and find a script of its own type in it, which I earlier attached to the prefab. The problem now is that when I run this "newCross" is whyever referenced to itself and I have no plan why
public void SpawnNextCrossroad(){
for (int i = 0; i < hookPoints.Length; i++) {
if (hookPoints[i].name != hookUsed) {
GameObject newCrossObj = crossroads[Mathf.RoundToInt(Random.Range(0, crossroads.Length - 1))];
Crossroad newCross = newCrossObj.GetComponent<Crossroad> ();
int distance = Mathf.RoundToInt(Random.Range (minDistanceBetweenCroasroads, maxDistanceBetweenCrossroads));
Vector3 posFac = hookPoints [i].position - calcPoints [i].position;
newCross.SpawnThis (posFac);
Instantiate (newCrossObj, (posFac * distance) + transform.position, Quaternion.identity);
}
}
Here a small sketch of my problem:
I'm sorry, what? Sorry it's a bit confusing but shouldn't you get newCross from the newly created instance? You are getting it from the prefab right now.
Answer by hexagonius · Dec 04, 2016 at 03:23 PM
that's because you're not doing what you describe in your sketches. you get the prefab, get ITS component and then instantiate it. You should do the GetComponent on the returned gameobject from the instantiate. BTW.
crossroads[Random.Range(0, crossroads.Length)];
suffices, because Range here returns an int and excludes the last possible value
Yeah, thats right. Here is how I solved it:
int whichCross = Random.Range(0, crossroads.Length - 1);
int distance = Random.Range ($$anonymous$$DistanceBetweenCroasroads, maxDistanceBetweenCrossroads);
Vector3 posFac = hookPoints [i].position - calcPoints [i].position;
GameObject newCrossObj = Instantiate (crossroads[whichCross], (posFac * distance) + transform.position, Quaternion.identity) as GameObject;
Crossroad newCross = newCrossObj.GetComponent<Crossroad> ();
newCross.SpawnThis (posFac);
And thank you for the hint. Didn't know that :)
you have it still wrong though. Length - 1 means they you will never get the last item. just use the length, Random accounts for that already
Your answer
Follow this Question
Related Questions
Hi everyone.need help with this. 1 Answer
CS0120 - Object reference required but it's already assigned. 0 Answers
Template object and script,GameObject scripts duplicated from a template game object 0 Answers
how to move a gameobject based on a dice roll 1 Answer
Having multiple UNET errors that I believe are caused by unity itself. Am I doing something wrong? 1 Answer