- Home /
Script sharing
I'll have to ask this again because I still don't understand:
I have a game object with a script attached. That game object has several children objects. The script reads variables entered from the Inspector.
Then I make duplicates of that object, each with different variables affecting the children objects. It doesn't work! The children follow the variable settings of the first duplicated object in the Hierarchy, not their respective ones.
My codes are something like this:
var thisShip = GameObject.Find("Ship");
thisShip.transform.rotation.eulerAngles.y = heading;
But all children objects from the different objects with attached script show the same "heading." What went wrong?
Answer by robertbu · Aug 08, 2013 at 09:36 PM
The problem is that GameObject.Find() searches the entire scene and returns the first game object with that name. Assuming your code is trying to assign the parent to the 'thisShip' variable, you can do:
var thisShip = transform.parent.gameObject;
Answer by Michel Verheughe · Aug 09, 2013 at 08:22 AM
I was so exited when I got up this morning (Norwegian time) reading your answer because it makes sense to add "parent." But ... I can't get it to work. ;-(
To test, I have only two ships, both sharing a script that is the model of the ship. They have different parameters such as initial speed, etc. entered from the Inspector window. This is because I will have to make many exercises, each with a different ship configuration.
Then, as children of the ship object, I have other objects with their own scripts. To get this to work, the children objects and their scripts must read the initial parameters of the parent ship object in the parent script. For example, in the script of a child object, I write:
var thisShip = transform.parent.gameObject; //the parent ship object
var thisModel = thisShip.GetComponent(shipModel); //the parent ship script
Debug.Log(thisModel.theName); //this should show the name of the ship
It only shows the name of one ship, probably the first one in the scene. What went wrong? Tanks in advance.
Even when I write:
var thisShip: GameObject;
and I enter the name of the ship object in the Inspector, when I then write:
var model = thisShip.GetComponent(ship$$anonymous$$odel);
and read a variable like:
Debug.Log(model.isName);
it shows, for both ships, the same name; not the different names of the two ships that are as the variables isName
I must say that I don't understand anything! ;-(
When making several copies of an object with a script, and children with scripts, yet having different parameters, here is how I found out it could work:
var parentObject = transform.parent.gameObject;
var thisChildObject = GameObject.Find(parentObject.name + "/child/grandChild");
Or, if the script is in the parent object:
var thisChildObject = GameObject.Find(this.name + "/child/grandChild");
Not the easy way around but it works. Perhaps it can help others.