- Home /
Instantiate with script component (c#)
Hello,
I can't realize what is wrong with my function:
public void dropItem()
{
itemScript script = new itemScript();
Transform newGO = (Transform) Instantiate(mouseItem.Model, characterTransform.transform.position, characterTransform.transform.rotation);
script = newGO.GetComponent ("itemScript") as itemScript;
script.name = mouseItem.name;
script.type = mouseItem.type;
script.Value = mouseItem.Value;
script.itemModel = mouseItem.Model;
script.texture = mouseItem.texture;
mouseItem = null;
}
I got this message from unity when the game called the function: "NullReferenceException: Object reference not set to an instance of an object" On this Line: 'script.name = mouseItem.name;'
Could anyone please help me?
Thanks in Advance.
Answer by ScroodgeM · Jul 22, 2012 at 07:51 PM
script.name = mouseItem.name;null reference is rather cause 'script' is null - possible caused by newGO havn't itemScript attached to it. use AddComponent instead of GetComponent if you want to create script on newGO object
to be sure what is error source write before line with error:
Debug.Log(script); Debug.Log(script.name); Debug.Log(mouseItem); Debug.Log(mouseItem.name);and check which line returns null
Answer by VoltCR · Jul 22, 2012 at 11:36 PM
Yeah, first I've tried to use 'AddComponent' and I got an error from unity: "Assets/Scripts/Inventory.cs(143,45): error CS1061: Type UnityEngine.Transform' does not contain a definition for
AddComponent' and no extension method AddComponent' of type
UnityEngine.Transform' could be found (are you missing a using directive or an assembly reference?) "
Ty.
you should use AddComponent on GameObject, not on Transform.
script = newGO.gameObject.AddComponent...
Your answer
![](https://koobas.hobune.stream/wayback/20220613074534im_/https://answers.unity.com/themes/thub/images/avi.jpg)