- Home /
Attaching an Model via Script.
So, while using C# I have to create a new GameObejct and apply Rigidbody as a component inside the script to use it..
How would I go about adding a model to this GameObject inside the script, without using the inspector.
Answer by TheHoboCoder · Jan 14, 2013 at 12:29 PM
GameObject newObj = new GameObject("ObjectName");
newObj.AddComponent <MeshRenderer>();
MeshFilter objMesh = newObj.AddComponent<MeshFilter>();
GameObject newMesh = Resources.Load("Cube") as GameObject;
objMesh.mesh = newMesh.GetComponent<MeshFilter>().sharedMesh;
http://docs.unity3d.com/Documentation/ScriptReference/GameObject.CreatePrimitive.html
There's also a constructor for GameObject that takes component types as params.
Answer by PAEvenson · Jan 14, 2013 at 12:21 PM
Instantiate the model:
Instantiate (prefab, new Vector3(0, 0, 0),Quaternion.identity);
parent it to your object with the script:
prefab.transform.parent = gameObject.transform;
I then suggest to zero out the position, rotation, and scale:
prefab.transform.localPosition = new Vector3(0,0,0);
prefab.transform.localScale = new Vector3(1,1,1);
prefab.transform.localEulerAngles = new Vector3(0,0,0);
This in no way told me how to add the model. I'm creating an object TO instantiate as an Arrow Projectile.
Ok...youre right, if you want to hardcode loading a resource you use Resources.Load like in theHoboCoder's answer. You also need to make sure that file is located in the Assets->Resouces folder inside your project.
Thank you, learned how to edit some other stuff I thought could only be done through the inspector from this post, thumbs up. Thanks again.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
(C#) Problem with animations not playing 1 Answer
Multiple Cars not working 1 Answer
Selecting a new object when it's created. 0 Answers
How to transfer colllider from OnTriggerEnter to Update 1 Answer