I want the Objects to be generated when I press ‘E’. Then they should get the HingeJoint Component, get renamed and get connected with the next part of the rope…
But they don’t connect. I get this error when I press ‘E’:
NullReferenceException: Object reference not set to an instance of an object
Hook.BindJoints () (at Assets/_Scripts/Hook.cs:60)
I understand what the error says, but I dont’t know how I can do it.
Code:
using UnityEngine;
using System.Collections;
public class Hook : MonoBehaviour {
public int partsNumber = 20;
public int curPart = 0;
public GameObject ropePrefab;
public GameObject player;
private GameObject conPart;
private GameObject ropePart;
bool partsCreated = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.E))
{
MakeRope();
if(partsCreated)
{
BindJoints();
}
}
if(curPart >= partsNumber)
{
curPart = 0;
}
}
bool MakeRope()
{
for(int i = 0; i < partsNumber; i++)
{
ropePart = (GameObject)Instantiate(ropePrefab, new Vector3(player.transform.position.x, player.transform.position.y + 2, player.transform.position.z + i), Quaternion.identity);
ropePart.name = "RopePart " + curPart;
ropePart.AddComponent<HingeJoint>();
HingeJoint hj = GetComponent<HingeJoint>();
curPart ++;
}
return partsCreated = true;
}
void BindJoints()
{
for(int i = 0; i < partsNumber; i++)
{
conPart = (GameObject)GameObject.Find("RopePart " + curPart + 1);
ropePart.hingeJoint.connectedBody = conPart.rigidbody;
}
}
}