首先,我的原如何發佈另一個可怕的獲得一個NullReferenceException訪問,我已經創建和檢索
的NullReferenceException組件時:對象引用不設置到對象的實例
但我已經走遍了網絡尋找一個解決方案,像現在的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;
}
}
PLAYER:
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:對象沒有設置爲一個對象
GroundCheck的一個實例。 OnTriggerEnter2D(UnityE ngine.Collider2D COL) (atAssets /腳本/ GroundCheck.cs:15)
這裏是我的場景:
這是我boxcollider(如果它幫助):
從[文檔]必要findtag(http://docs.unity3d.com/ScriptReference/Component.GetComponent.html) ,_「如果遊戲對象有一個連接,返回Type類型的組件,如果不是,則返回null。」_看起來'GetComponent'返回'null',即使它被添加到屏幕截圖中。如果你在'Start()'方法的行中放置一個斷點,是否有任何東西被賦值給該變量? –
可能重複[什麼是NullReferenceException,我該如何解決它?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) –
OP包含一個屏幕截圖,表明玩家_應該可用,然後他得到的代碼似乎應該讓他創建的玩家。他甚至包含了完整的堆棧跟蹤,其中包括確切的投擲線。這不是真正的追蹤'NullReferenceException'的情況,而是Unity中有經驗的人查看所有提供的細節,並可能注意到配置錯誤。 –