How to assign my players transform to an Instantiated object?
Hi! I'm making a 2D game and have a player that shoots a ball and im trying to teleport to its position when i press a button. But i keep getting and error : NullReferenceException: Object reference not set to an instance of an object MoveFire.Teleport () (at Assets/2DPractice/Scripts/MoveFire.cs:58) MoveFire.Update () (at Assets/2DPractice/Scripts/MoveFire.cs:29)
public int moveSpeed = 250;
public GameObject player;
private Transform myTransform;
private void Awake()
{
player = GameObject.Find("Player");
myTransform = GetComponent<Transform>();
}
void Update()
{
transform.Translate(Vector3.right * Time.deltaTime * moveSpeed);
if (Input.GetButtonDown("Fire1"))
{
Teleport();
}
}
public void Teleport()
{
Debug.Log("i want to get here");
player.transform.position = myTransform.position;
}
I'm still learning but this is really annoying me, so any help is welcomed! Thanks.
First, you don't need
myTransform = GetComponent<Transform>();
Your script already has a reference to the transform. In fact, you are using it in your update with transform.Translate.
The null ref is because it didn't find the player object. Are you sure you spelled it correctly? The player gameObject is really named "Player"?
@Vega4Life Thanks for the myTransform part. But I double checked the name and it's correct.
Are you able to just reference the player object straight into this script via the inspector? Ins$$anonymous$$d of using find?
Your answer
![](https://koobas.hobune.stream/wayback/20220612184031im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to make a Teleporter Pad send Player to other random Teleporter Pad? 1 Answer
2D Power up script not working 0 Answers
Assign a prefab as childs to several gameobjects 1 Answer
How can I teleport the player when a bonus level timer runs out? 0 Answers
Can't make player character teleport from one side of screen to another. 1 Answer