- Home /
How Do I Get a Script to Reference the GameObject When Using AddComponent?
I am adding a script named "Part" to a part of a 3D model at runtime like this:
private var _Part;
var obj=Parts.transform.Find(partName);
_Part=obj.gameObject;
_Part.AddComponent("Part");
_Part.GetComponent(Part).init(this);
In the "Part" script I have this:
function init(parentRef){
this.AddComponent("BoxCollider");
}
but it fails (I think) because "this" doesn't reference the _Part game object i.e. the game object it is a component of. How can I reference the game object?
The error I get is:
MissingMethodException: Method not found: 'Part.AddComponent'.
Answer by Demigiant · Dec 14, 2011 at 02:52 PM
MonoBehaviour scripts can always refer to their gameObject with the property gameObject
. Thus this would suffice:
this.gameObject.AddComponent( "BoxCollider" );
Thanks! I tried this.AddComponent and gameObject.AddComponent, but not this.gameObject.AddComponent.
Your answer
Follow this Question
Related Questions
Loading Scripts onto GO before in-game scene 1 Answer
Adding Prefab Components 1 Answer
Will using AddComponent frequently lower performance? 1 Answer
Error in AddComponent 1 Answer
How can I add external-assets(C#) 1 Answer