简体   繁体   中英

How to reference a Player in unity

The code (GameObject reference) doesn't show up so I need a different way to reference a player. I have not tried much though.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CamaraBehaviour : MonoBehaviour {
    public Object Player;
    public float yOffset = 3.0f;
    public float zOffset = 10.0f;
    Vector3 newPos = Player.transform.position;
    // Use this for initialization
    void Start () {
    }

    // Update is called once per frame
    void Update () {
        newPos.y = newPos.y + yOffset;
        newPos.z = newPos.z + zOffset;
        transform.position = newPos;
        transform.LookAt(player.transform);
    }
}

This is my camera fixing code. Which is why I need the reference in the first place. I thank you for the help (NO gmae written please the school blocks the word so if you reply with the word I wont be able to access the site).

The Player does not show up in the inspector because it's type, Object is not serializable. You want to use GameObject for Unity objects.

public GameObject Player;

You have a few other errors in this code.

  1. You can't set the newPos using a reference to another object outside of a method. Do this in Update() instead.

     Vector3 newPos; // Update is called once per frame void Update () { newPos = Player.transform.position; // your other code }
  2. There is a typo on the last line of update, where the P in Player needs to be capital (that's what you named your variable).

     transform.LookAt(Player.transform);

EDIT: However, since you only seem to be using the Player.transform anyways, you might as well go ahead and reference the transform component instead.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CamaraBehaviour : MonoBehaviour {
    public Transform Player;
    public float yOffset = 3.0f;
    public float zOffset = 10.0f;
    Vector3 newPos;

    // Update is called once per frame
    void Update () {
        newPos = Player.position;
        newPos.y = newPos.y + yOffset;
        newPos.z = newPos.z + zOffset;
        transform.position = newPos;
        transform.LookAt(Player.position);
    }
}

If the script is attached to the player you can do this:

private GameObject player;

void Start()
{
    player = GetComponent<GameObject>();
}

However, you can make a public variable as demonstrated in the other answer by Marcus.

But... If you want to find the game object at runtime, you can also do this:

private GameObject player;

void Start()
{
    player = GameObject.FindWithTag("Player");
}

You just have to be certain to tag your player accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM