Can't assign a game object to another game object which is a property of a class?

Hello

I am writing a struct for Class Robot, which is consists of an array of RobotJoints. The RobotJoints class itself consists of a Game Object, two list of doubles, and an array of integer.
The code does not work because of NullReferenceException in the line ( this.robotJoints_.joinT = gO*; )!!!_
Please find the code here:
public class RobotJoints
_
{*_

* public GameObject joinT = new GameObject ();*
* public List constraintsMin = new List();*
* public List constraintsMax = new List();*
* public int[] ActiveDoFs = new int[6];*

* public RobotJoints()*
* {*
* this.joinT = new GameObject ();*
* this.constraintsMin = new List();*
* this.constraintsMax = new List();*
* this.ActiveDoFs = new int[6];*
* }*
* public RobotJoints(GameObject gObj)*
* {*
* this.joinT = gObj;*
* this.constraintsMin = new List ();*
* this.constraintsMax = new List ();*
* this.ActiveDoFs = new int[6];*
* }*

}
public class Robot
{
* public RobotJoints[] robotJoints;*
* public Robot()*
* {*
* this.robotJoints = null;*
* }*
* public Robot(GameObject[] gO)*
* {*
* for(int i=0; i<(gO.Length);i++)*
* {*
this.robotJoints_.joinT = gO*;// There is something wrong here…
}
}
}*

and this is the error:
NullReferenceException: Object reference not set to an instance of an object
Any suggestion is greatly appreciated. Thanks_

2 Answers

2

You don’t show any code that would set robotJoints to anything else than null. After doing that you must also create the contents of that array, since arrays of reference types are initialized with (filled with) null unlike value type arrays (int).

public Robot(GameObject[] gO)
{
    this.robotJoints = new RobotJoints[go.Length];          
    for(int i=0; i<(gO.Length);i++)
    {
        this.robotJoints *= new RobotJoints();*

this.robotJoints_.joinT = gO*;// There is something wrong here…
}
}*_

Fixed the mistake @Seyed spotted. Copy pasting on mobile while commuting proved error prone once again :)

The problem is not solved... I am still stick to the problem... :-)

Fixed again. There was one more idiotic typo there X-)

Thank you man... this one worked :-)

If it worked, accept the answer please (click the checkmark next to it). That's how Unity Answers works :)

I don’t think this.robotJoints*.joinT = new RobotJoints[gO.Length] is right, since joinT is a game object which is declared in the Class Robotjoints.*
Each robotJoints has only one game object named, joinT.

Please post comments to answers as comments and answers to questions as answers ;)