访问我创建和检索的组件时出现 NullReferenceException

Getting a NullReferenceException when accessing a component that I've created and retrieved

首先,我对 post 另一个可怕的

多么原始

NullReferenceException: Object reference not set to an instance of an object

但我已经在网上搜索了大约 2 个小时的解决方案,但一无所获...这是我拥有的两个脚本:

接地:

using UnityEngine;
using System.Collections;

public class GroundCheck : MonoBehaviour {

private Player player;

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

void OnTriggerEnter2D(Collider2D col)
{
    player.grounded = true;
}

void OnTriggerExit2D(Collider2D col)
{
    player.grounded = false;
}
}

玩家:

using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {

public float maxSpeed = 3;
public float speed = 50f;
public float jumpPower = 150f;

public bool grounded;

private Rigidbody2D rb2d;
private Animator anim;

// Use this for initialization
void Start () {

    rb2d = gameObject.GetComponent<Rigidbody2D>();
    anim = gameObject.GetComponent<Animator>();
}

// Update is called once per frame
void Update () {

    anim.SetBool("Grounded", grounded);
    anim.SetFloat("Speed", Mathf.Abs(Input.GetAxis("Horizontal")));
}

void FixedUpdate()
{
    float h = Input.GetAxis("Horizontal");

    rb2d.AddForce((Vector2.right * speed) * h);

    if (rb2d.velocity.x > maxSpeed)
    {
        rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
    }

    if (rb2d.velocity.x < -maxSpeed)
    {
        rb2d.velocity = new Vector2(-maxSpeed, rb2d.velocity.y);
    }
}
}

准确的错误是:

NullReferenceException: Object reference not set to an instance of an object

GroundCheck.OnTriggerEnter2D (UnityEngine.Collider2D col) (atAssets/scripts/GroundCheck.cs:15)

这是我的场景:

这是我的 boxcollider(如果有帮助的话):

您的地面检查脚本与播放器脚本不在同一个对象上,这意味着您不能使用 getcomponent 来获取播放器脚本。所以你没有将播放器变量设置为导致错误的任何东西。将玩家变量设置为在编辑器中具有玩家脚本的游戏对象,然后在您的启动方法中使用 player.GetComponent();

如果 GroundCheckPLAYER class 都在同一个 GameObject 上,则更改 GroundCheck class 的 Start() 方法像这样:

void Start()
{
    player = gameObject.GetComponent<Player>();
}

如果它们不在同一个游戏对象上,则使用以下代码:

void Start()
{
    GameObject playerObj = GameObject.Find("Name of gameObject that player script is in that");
    player = playerObj.GetComponent<Player>();
}

PLAYER class 中,将 static 修饰符添加到 grounded 的定义中:

public static bool grounded;

void OnTriggerEnter2D(Collider2D col) <-- 在collider参数请求gameObject中,getcomponent to col是首选,只控制对象碰撞是否为player. col.gameObject.getcomponent<Player>().grounded=true;

if(col.Name.Equals("Player")
{
    col.gameObject.getcomponent<Player>().grounded=true;
}

我遇到了类似的问题。我希望它有帮助 http://docs.unity3d.com/ScriptReference/Collision2D.html

Collider2d有gameobject组件,触发enter获取Collider这个对象。

http://docs.unity3d.com/ScriptReference/Collider2D.OnCollisionEnter2D.html 请参阅在对撞机中使用的示例(不是触发器只是示例)使用,访问游戏对象。

当对象(玩家)在 OnTriggerEnter、Exit 或 Stay 事件中传递参数时,不需要查找标签