Csharp and prefabs

Hello Unity community.

I’m having a bit of trouble adding my prefab to my program, using C#. Now I got it perfectly working in javascript.
Here’s my code:

using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {
	public GameObject prefab_player;
	Object player;	
	
	public void Start () {
		gameObject.AddComponent(prefab_player);	
	}

	void Update () {
	}
}

This ofcourse doesn’t work, but how would you do it then? (I also want the object, when created, to be stored away in the player variable)

Hope to hear from you soon :slight_smile:

  • Chris

Welcome aboard Zigs! We need nore C# people round here.

Whatever you do … don’t do this !! :wink:

Msg(“Instantiate Grenade”);
Transform t = Instantiate(GrenadeModel, MountLeft.position , Quaternion.identity)as Transform;

I always got caught leaving off the “As Type”. C# is pretty demanding.


I just re-read your post and I think your title asks for a prefab, but you are really looking to add a component. If you want to a component or script, you can add it like you are doing , buut give it a script ot or component. ex gameObject.AddComponent(“Rigidbody”);

buuut maybe you want to add a prefab and “parent” it to your gameobject, in which case you could find the object you want to parent it to by doing something like this:

InstGrenade = GameObject.Find(“Grenade_pf(Clone)”);
InstGrenade.transform.parent = MountLeft.transform;

hth

Thanks for the fast reply, but I’m not sure I fully understand.
What I’m trying to, is to get an object into the world, created from a prefab. No need to get parent/childing involved right now.

Fromt the manual Instantiating Prefabs at runtime

using UnityEngine; 
using System.Collections; 

public class Player : MonoBehaviour { 
   public GameObject prefab_player; 
   Object player;    

   public void Start () { 
      //fyi: use a different transform to create the object at another location
      Instantiate(prefab, transform.position,transform.rotation);
   } 

   void Update () { 
   } 
}

Oh ofcourse! I am an idiot! I assumed that AddComponent(); was the way to create stuff when using C#, but now i see how stupid that was of me… got it working now. :slight_smile:

Thanks a bunch both of you :smile:

  • Chris