- Home /
Is it possible to replace the script on a gameobject with another of the same type?
Hello,
I'm trying to replace the script of an instantiated gameobject with one of the same type I have stored in a List. Here's the code, which is throwing an error on the final instruction.
The error is: The object of type turret gun scripthas been destroyed but you are still trying to access it
Is this sort of script replacement possible? And if so, is it a good idea?(i.e. won't cause unexpected behaviour) Thanks for your time!
// Instantiate and get reference to Gameobject
GameObject tempTurret = (GameObject)Instantiate(turretPrefab2, turretScriptList[i].GetTurretPosition(), Quaternion.identity);
if(tempTurret == null)
{
Debug.Log("TurretSceneScript1.PlaceExistingTurrets: Turret1 is null");
}
// Get the current turret's script
TurretGunScript currentTurretScript = (TurretGunScript) tempTurret.transform.Find("Gun").GetComponent("TurretGunScript");
// Get the stored Script in tempsave
TurretGunScript replacementScript = (TurretGunScript) turretScriptList[i];
// Replace the current script
currentTurretScript = replacementScript;
// Set the texture appropriate to that type
currentTurretScript.SetTurretTexture();
Answer by 1337GameDev · Feb 19, 2013 at 03:52 PM
When you destroy the component or remove , references to it dont work. So storing a reference to it after it is deleted will return null. The reference just indexes its memory address, when you delete it, the object is considered "deleted" in memory and not allowed to be accessed. Components normally have non-static members anyways and would cause more problems.
Use the add component method to add a script at runtime. You can tore references to scripts as objects, but if it was attached to a gameObject, I believe you have to attach it first, and then update the reference to it.
Answer by Owen-Reynolds · Feb 19, 2013 at 04:57 PM
The net effect would be the old script's global variables are replaced by the globals in the new one?
Seems like it might be easier to write a small routine to copy the variables you need (like the gun type and ammo prefab?)
Yeah, that's how you would do it the easiest. You would need a script that stores Hesse values and then removes the script you want from your gameObject and then uses AddComponent to add a new script and copy values over.
Yep, Owen, you're right on this one. Got it working (kinda) by removing and adding a new script but there were a lot of errors (broken references and others). I ended up just writing a method to copy what is needed, and it worked off the bat. Thanks for the suggestion!