Get Component isn't working too well
Hello again Unity Community;
I am creating my first game (not following any tutorials and etc.) and I seem to have difficulties with the command: GetComponent<>;
Down bellow is the section of the code where I worked on the command:
if (i == 2) {
GetComponent<WPmsslCTRL> ().parabolCtrl();
i = 0;
}
}
Which should run the the function:
public void parabolCtrl()
{
for (x = -50 ; x <= 50; x++)
{
waypointNum.Add (Instantiate (wayPoint, new Vector3 (x,- (0.09f)*(x*x)+10, 0), Quaternion.identity)); // just like y= ax^2 + bx + c
}
}
Unfortunately, I keep getting this error:
NullReferenceException: Object reference not set to an instance of an object testSpawn.Update () (at Assets/Script/testSpawn.cs:58)
I made sure that the component is attached to a game object and both the component and the game object are set active. I am not clear on the issue with my getComponent.
Answer by sisse008 · Jan 09, 2018 at 01:54 PM
if the WPmsslCTRL component is attached to a different gameobject (different than the gameobject this script is attached to), than you need to reference that gameobject and only then reference the WPmsslCTRL component:
public GameObject go;
void YourFunction()
{
WPmsslCTRL _ctrl = go.GetComponent<WPmsslCTRL> ();
if(_ctrl != null)
{
_ctrl.parabolCtrl();
}
}
*Just realized
Thanks so much, I can't believe I spent an hour trying to resolve this issue, guess I need to work more in coding logic and Unity and get used to it
Your answer
Follow this Question
Related Questions
How do you use a Component slot? 1 Answer
Game Manager can't decide what the instance of the object is despite just making an instance of it 1 Answer
Toogle Parent to Camera Function - Google Cardboard 0 Answers
How to test what material is applied to an object. 0 Answers
How to correctly handle NullReferenceException when using GetComponent<>? 1 Answer