Hi guys,
I’m just starting to learn Unity and am developing Snake as a way to learn the engine and C#.
I’m having a lot of trouble getting the snake body to work. At the moment, I have a snake head (just one cube that I can control), and I want to write a script so that when I press spacebar, it creates a body segment. I can get the script to instantiate a new body segment every time I hit space bar, but I can’t move the body segments after they’ve been initiated.
I know this is a pretty basic topic and there’s a lot of stuff here about moving gameobjects, but I’ve been searching this forum and reading answers for a while, and still can’t quite figure it out. Could you guys take a look a the, and let me know what I’m doing wrong?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class SnakeController : MonoBehaviour {
enum moveDirection{up, down, left ,right};
moveDirection d;
List<Vector3> bodyPositions = new List<Vector3>();
Vector3 headPosition = new Vector3(0, 0, 0);
public GameObject snakeBodyPrefab;
private GameObject clone;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
bodyPositions.Add(transform.position);
headPosition = transform.position;
//Control the movement
if (Input.GetKey("up"))
d = moveDirection.up;
if (Input.GetKey("down"))
d = moveDirection.down;
if (Input.GetKey("right"))
d = moveDirection.right;
if (Input.GetKey("left"))
d = moveDirection.left;
if (d == moveDirection.up) {
transform.position += new Vector3(0, 0, 0.1f);
}
if (d == moveDirection.down) {
transform.position += new Vector3(0, 0, -0.1f);
}
if (d == moveDirection.right) {
transform.position += new Vector3(0.1f, 0, 0);
}
if (d == moveDirection.left) {
transform.position += new Vector3(-0.1f, 0, 0);
}
Debug.Log(headPosition.x.ToString());
//Control growth of snake
if (Input.GetKey(KeyCode.Space)) {
Debug.Log("grow");
clone = Instantiate(snakeBodyPrefab, transform.position, Quaternion.identity) as GameObject;
clone.transform.Translate(new Vector3(0,0,0));
}
}
}
This is the part I’m mainly having trouble with:
clone = Instantiate(snakeBodyPrefab, transform.position, Quaternion.identity) as GameObject;
clone.transform.Translate(new Vector3(0,0,0));
If I don’t include the second line, it’s fine, and I just keep dropping body segments where I move. But when I try to move these segments, I get “NullReferenceException: Object reference not set to an instance of an object”
Any advices would be greatly appreciated. Thank you,
Matt