Adding a script to an instance during the game

I’ve got a player model (a plane), and “playerScript” that allows the plane to move. As the plane starts in a hanger with other planes, I thought I’d make a prefab out of the plane, and then I can dot other planes around as I see fit.

Obviously the main problem with this is that “playerScript” is attached to every plane, so the player can move them all at the same time!

So I figured that I’d remove the script from the prefab, and then I can just add some code to attach the script to the one plane that the player will control.

So here’s where I’ve got to:

var playerFighterPrefab : Rigidbody;

function Start () {
	playerInfoScript.playerLives = 9;
	var playerFighter = Instantiate(playerFighterPrefab, Vector3 (5,5,5), Quaternion.identity);
	
	if (playerInfoScript.playerLives > 1) {
		for (var y = 1; y <= playerInfoScript.playerLives; y++) {
			var spareFighter = Instantiate(playerFighterPrefab, Vector3 (5*y,5,5), Quaternion.identity);
		}
	} 

playerFighter.transform.Rotate(Vector3.up, 270);

}

It’s attached to an empty object in the scene. It creates the player plane, and then loops through and creates some spare planes.

I guess I need to use something like:

playerFighter.AddComponent("playerScript");

But it tells me: MissingMethodException: Method not found: ‘UnityEngine.RigidBody.AddComponent’.

The playerScript is not currently attached to anything.

I’m sure it’s something simple I’m missing, I’m just not sure what it is :slight_smile:

playerFighter.gameObject.AddComponent(“playerScript”);

Thanks, that works. I think that must have been about the only option I didn’t try.

I had the same exact issue, thanks for posting!

But I realized that I have to set variables in the script as it’s being attached… maybe it’s easier to have it attached with all the settings, then destroy it if it doesn’t meet the required parameters (instead of vice-versa).