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*.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*;*_

* // Replace the current script*
* currentTurretScript = replacementScript;*

* // Set the texture appropriate to that type*
* currentTurretScript.SetTurretTexture();*

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?)

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.