NullReferenceException: Object reference not set to an instance of an object Worp.Update () (at Assets/Scripts/Worp.cs:33)
So yh this scrpt is suppose to give my player the ability to swap his position with any gameobject clicked on with a tag "swappable", but so it doesn't work and only gives the error above
using UnityEngine;
using System.Collections;
public class Worp : MonoBehaviour {
//This scipt is attach to my thirdperson player
public Transform object1; //player
Transform object2;
Vector3 targetposition;
public float range = 2;
void start()
{
}
void Update()
{
if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if(hit.collider.tag== "swappable")
{
Debug.Log("Right object");
object2.transform.position = hit.transform.position;
Vector3 tempPosition = object1.position;
object1.position = object2.transform.position;
object2.transform.position = tempPosition;
}
}
}
}
}
Is this the whole script? What is object2? You haven't assigned anything to the variable, so it's always null and you get an exception when trying to change its position.
Yeah, you're immediately trying to access some member of "object2" even though it has not yet been set to anything, there for it does not have any members such as "transform".
Immediately after your Debug.Log line, use this: object2 = hit.transform;
Oh and, object2 is already a "transform", so you don't need to access "object2.transform", just shorten that to "object2".
Your answer
Follow this Question
Related Questions
Operator `+' cannot be applied to operands of type `UnityEngine.Vector3' and `float' 3 Answers
make a gameobject move to another gameobject that was selected by mouse click? 1 Answer
Unable to correctly use game objects? 2 Answers
How would I project a Gameobject onto the surface of another? 0 Answers