Script is losing connection to different game object after respawn

I have a problem and I cant find solution for it anywhere ! So I have game object Ball with Collision script atached to it .In that Collision script I am accsessing variable in other script that is atached to different game object !This far all works fine !
Problem starts whe I destroy Ball and respawn it back from prefab folder ! .Once Ball is respawned the other game object with its script is no longer asigned to Ball in inspectors menu .So I have no more access to that script and variable in it.
after respawn in inspectors menu it says None (Game object) .
So how can I automaticaly asign back that object after Ball respawns ?

Depending on how one interprets the word, you can’t automatically assign the newly spawned GameObject to your field. But you can write code that assigns it for you, and I guess one could call that “automatically” :slight_smile:

First off: The Instantiate function you are using to spawn your new ball will return a reference to that ball. So instead of


you can do

var myNewBall = InstantiateBallPrefab(ballPrefab);

and then you can do whatever you want with that reference. For example, you can put it in another script’s field:

theOtherScript.ballField = myNewBall;

Of course, if you don’t do anything else with that reference, you can assign it directly without the local variable.

theOtherScript.ballField = InstantiateBallPrefab(ballPrefab);

While we’re at it, you can use this to initialize your spawned object:

myNewBall.transform.localScale = * someNumber;

Another way would be to add a component to your ball prefab that registers itself wherever you want in Start().