This looks like JavaScript, but you’re declaring theTown in a C# style. Does this even compile, as-is?
You’re calling Instantiate on a Transform, so it will return a Transform. Your cast operation will compile, but won’t run properly.
Something like this might work, instead:
var theTown : Transform = Instantiate(Town, Vector3.zero, Quaternion.identity);
Anyway, the immediate problem is that you’re storing a reference to theTown, but not keeping it. As soon as the Start() function ends, the variable is lost. To keep the variable, you’ll need to declare it at a higher scope.
So, something like this:
var Town : Transform;
var theTown : Transform;
function Start() {
theTown = Instantiate(Town, Vector3.zero, Quaternion.identity);
}
Now, all of this could still fail if your other script tries to access theTown before it’s set. Accessing other scripts during Start() is prone to errors if you’re not careful. If you read the variable, later, this is less of a problem.
I finally resolved the problem and this works really fine, thanks you rutter for the help, here is how you need to do for instantiate a prefab in a script and destroying it in an other script :
firstScript.js
var Cube : Transform; // This is the variable where you specify the prefab to instantiate (in unity with drag and drop)
var theCube : GameObject; // Name of variable that will be used to destroy
function Start () {
theCube = Instantiate(Cube, Vector3(0, 0, 5), Quaternion.identity).gameObject; // Instantiate the prefab and put the gameObject into "theCube"
}
secondScript.js
var firstscript : firstScript; // "firstscript" is a variable name of your choice and "firstScript" is your script name
function Update () {
if (Input.GetMouseButton(0)) {
firstscript = GameObject.Find("EmptyGameObject").GetComponent(firstScript); // Here we get the script component into the Empty GameObject I created (manually)
Destroy(firstscript.theCube); // then call "firstscript" dot your variable name of the clone prefab
}
}
The game hierarchy looks like this in this example :
EmptyGameObject wich contains as a component the script “firstScript.js”
RandomEmptyGameObject wich contains the “secondScript.js”