Function calling on undesired GameObject

The forum topic for my problem can be found at this link

http://forum.unity3d.com/viewtopic.php?p=386432#386432

I just posted this here to get my question more exposure...

Edit: To Skovacs1: Thanks that makes sense but the reason I wasn't passing it as a parameter was because if Destroy() is called on Cube1, then Cube2 will stop moving because the function that is making Cube2 move is on a script attached to Cube1. That's a big problem... But if I was somehow able to call the function directly on Cube2 then it wouldn't matter if Cube1 is destroyed, and Cube2 would keep having the function called on it.

Edit2: I solved this after making the MoveSomewhere() a static function, now even when Cube1 is destroyed, Cube2 keeps moving. Hopefully this is the right way to do this...I hope I'm not creating huge design flaws.

Please don't post in both. The forums are very cluttered as it is.

Your problem is not that you are trying to call a function on an undesired gameobject, but that you don't understand the concept of variable scope and what the scope of the object local variable transform is. Consider what your code does:

  • You define a class (MoveScript) and give it a public function.
  • Your public function calls `transform.Translate(1,1,1)` - transform is that of the object the script is attached to.
  • You define a second class (GetMove) and give it a public function that will be called by the system at start.
  • This public function gets the instance of the previous class that is attached to Cube1 and calls the function on it. Since transform is a local variable defined in the object to which the script is attached, of course when you get the instance attached to Cube1, transform is that of Cube1.

You seem to think that the function should be grabbing the transform local to Cube2, but that is incorrect.

What you could do is define a function that takes in a transform as a parameter and then translates the transform that was passed in. Then, when you call this function, passing in the transform that you want changed (from Cube2), you will get the desired effect.