Im new to scripting and read through several questions but im not able to write the script yet.
I have a game where i can switch levels through a portal and i want to destroy an object in level 1 through a trigger in level 2.
Can someone help me putting it together? I started with something like this:
function OnCollisionEnter(myCol: Collision){
if(myCol.gameObject.name == "Cube666")
Destroy(myCol.gameObject);
}
But nothing happens so far. I added it to the Object which i want to be the trigger.
You can’t destroy objects in another scene, since that scene is not even loaded in memory. The objects don’t exist until you load it (and then the original scene disappears).
What you can do, is create an empty game object called “Persistent_Object” or something like that, and call DontDestroyOnLoad(this)
in the object’s Start()
method. This tells Unity3d to keep this object when you switch scenes.
Now what you can do with this object, is hold a name (use a hashmap) of all the object names that you want ‘destroyed’ upon loading another scene.
Then, in each scene, create an object called “Destroyer”. This object in the Start()
method can get the list of objects to destroy from the Persistent_Object
, and destroy them right away.
You can’t directly do anything to objects in different scenes just because only the current scene is loaded. In this case, when you return to level 1 all objects will be instantiated anew - including the one you want to destroy.
The only way to do what you want is to pass info between scenes and, when loading scene 1, do not instantiate the object (if it’s created by code) or immediately deactivate it (if the object was placed in scene in the Editor).
Passing info between scenes can be done with static variables, persistent objects or via PlayerPrefs. I personally prefer static variables: they are fast, and are created as soon as the game starts - this helps a lot when testing higher levels, since no persistent objects need to be created in previous levels.
Let’s create a script called Level1.js, which takes care of objects that may be created or destroyed by other levels, and suppose that you want to destroy the object Door23 (placed in scene in the Editor) and eliminate the monster Enemy14 (instantiated by code) when you reach the Cube666 trigger in level 2:
// Script Level1.js:
static var door23enabled = true;
static var enemy14enabled = true;
function Start(){
// activate or deactivate a scene object:
GameObject.Find("Door23").SetActive(door23enabled);
// don't instantiate enemy14 if it was disabled in another level:
if (enemy14enabled) Instantiate(enemy14prefab,...);
...
}
In order to destroy these objects, set the static variables in the player script:
function OnTriggerEnter(other: Collider){
if(other.name == "Cube666"){
Level1.door23enabled = false; // door23 won't exist anymore
Level1.enemy14enabled = false; // enemy14 won't bother you anymore
}
}