unity3d 列表出现Unity空引用异常[重复]

jhkqcmku  于 2023-02-05  发布在  其他
关注(0)|答案(1)|浏览(263)
    • 此问题在此处已有答案**:

What is a NullReferenceException, and how do I fix it?(27个答案)
4小时前关门了。
所以做一个小行星游戏,尝试在4个小行星上产卵,每个小行星在每一边的中心部分。代码如下所示为spawnerScript和初始化方法。
出现几个错误/警告:
空引用异常:未将对象引用设置为对象(UnityEditor. PropertyHandler. isArrayReordable)的示例
当存在热控件时,不应捕获
如果有人能指出为什么它会给出这个错误,我们将不胜感激

[SerializeField] GameObject prefabAsteroid;
List<GameObject> asteroids = new List<GameObject>();
List<Vector3> screenSides = new List<Vector3>();
// Start is called before the first frame update
void Start()
{
    //get screen numbers
    float screenHeight = ScreenUtils.ScreenTop - ScreenUtils.ScreenBottom;
    float screenWidth = ScreenUtils.ScreenRight - ScreenUtils.ScreenLeft;

    //collect all screen sides
    screenSides.Add(new Vector2(ScreenUtils.ScreenLeft,screenHeight/2));
    screenSides.Add(new Vector2(ScreenUtils.ScreenTop, screenWidth / 2));
    screenSides.Add(new Vector2(ScreenUtils.ScreenRight, screenHeight / 2));
    screenSides.Add(new Vector2(ScreenUtils.ScreenBottom, screenWidth / 2));
    //loop through each direction(Up,Left,Down,Right) and
    //Instantiate asteroid on center of each side.
    int i = 0;
    foreach (Direction dir in System.Enum.GetValues(typeof(Direction)))
    {

        GameObject pa = Instantiate<GameObject>(prefabAsteroid);
        //add to list
        asteroids.Add(pa);
        pa.GetComponent<Asteroid>().Initialize(dir, screenSides[i]);
        i++;
    }
public void Initialize(Direction direction, Vector2 location)
{
    transform.position = location;
    float angle = Random.Range(0 * Mathf.Deg2Rad, 30 * Mathf.Deg2Rad);
    Vector2 forceMagnitude = new Vector2(Random.Range(minImpulse, maxImpulse), Random.Range(minImpulse, maxImpulse));
    if(direction == Direction.Right)
    {
        angle +=-15*Mathf.Deg2Rad;
    }
    else if (direction == Direction.Left)
    {
        angle +=165 * Mathf.Deg2Rad;
    }
    else if (direction == Direction.Up)
    {
        angle += 75 * Mathf.Deg2Rad;
    }
    else if (direction == Direction.Down)
    {
        angle += 255 * Mathf.Deg2Rad;
    }
    Vector2 moveDirection = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));
    rb.AddForce(forceMagnitude * moveDirection, ForceMode2D.Impulse);
}

尝试将示例化对象存储到列表中,尝试从列表中获取组件,但仍然出现相同错误

luaexgnf

luaexgnf1#

修好了。
错误是刚体组件"rb"不在初始化中(在Start()方法中,但此时尚未运行),因此被视为空。刚刚注意到Ann. L说了同样的话

相关问题