- Home /
Storing collided gameObject array index
Hi Everyone,
I have 3 gameObject players in array.
public GameObject [] player;
player = GameObject.FindGameObjectsWithTag ("PlayerBlue");
if (collision.gameObject.tag == "PlayerBlue")
{
i = (store array index here)
transform.parent = player[i].transform;
}
How do I store the index of collided game object? I want to make collided player to be the parent of the ball.
Please advise. Thank you.
Hi, I'd like to suggest not to use the Find method.. I remember someone from Unity stating that it's a resource hog and that you should most definitely figure out a different way of doing the same task.
Personally I just check the gameObject name (gameObject.name) because it won't change (in my case). As for the array. I'm not sure what exactly you mean by index. You could try storing information about the transform in an array in case if you plan on referencing that info later on.
It sounds a lot like a footBall/Soccer game so, why not just attach the script to the ball and change the parent of the object on Collision? Something like...
OnCollisionEnter(Collision obj){
transform.parent = obj.transform;
}
Hi Shadox,
Thanks for the info. This script is attached to Ball and indeed this is a soccer game >.<
I tried your method and it works. But for future, the ball will only become child of player. For your method, if ball collide with a wall, the wall will become parent of the ball which does not make sense.
Thanks for the info!
Oh, sorry about that, didn't think of that.
You could try to mark gameObjects in some way. Like some variable that , if it exists or is set to some specific value (or the gameObject has some specific name or namePattern) means that it's a character on the field and not a wall or something else.
But from the looks of it you already got your answer, so.. :)
Answer by mattssonon · Oct 01, 2013 at 11:45 AM
You could do it like this:
if (collision.gameObject.tag == "PlayerBlue")
{
for (int j = 0; j < player.Length; j++) {
if (player[j] == collision.gameObject) {
i = j;
transform.parent = player[i].transform;
break;
}
}
}
We compare the tagged game objects with the collision game object and save it if it's the right one.
Your answer
Follow this Question
Related Questions
[C#] Buttons through an Array. 1 Answer
A problem with intersection detection 1 Answer
Array empties values on RunTime? 1 Answer
Selecting Object From Top Causes NullReference 1 Answer
Index out of Range Exception Error 2 Answers