为什么我在对象完成移动后继续获得null异常?

时间:2018-04-13 22:29:47

标签: c# unity3d

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

public class BoidFlocking : MonoBehaviour
{
    public Vector3 velocity;

    private float cohesionRadius = 10;
    private float separationDistance = 5;
    private Collider[] boids;
    private Vector3 cohesion;
    private Vector3 separation;
    private int separationCount;
    private Vector3 alignment;
    private float maxSpeed = 15;

    private void Start()
    {
        InvokeRepeating("CalculateVelocity", 0, 1f);
    }

    void CalculateVelocity()
    {
        velocity = Vector3.zero;
        cohesion = Vector3.zero;
        separation = Vector3.zero;
        separationCount = 0;
        alignment = Vector3.zero;

        boids = Physics.OverlapSphere(transform.position, cohesionRadius);
        foreach (var boid in boids)
        {
            cohesion += boid.transform.position;
            if (boid == null)
                print("It's null !!!!!");

            alignment += boid.GetComponent<BoidFlocking>().velocity;

            if (boid != GetComponent<Collider>() && (transform.position - boid.transform.position).magnitude < separationDistance)
            {
                separation += (transform.position - boid.transform.position) / (transform.position - boid.transform.position).magnitude;
                separationCount++;
            }
        }

        cohesion = cohesion / boids.Length;
        cohesion = cohesion - transform.position;
        cohesion = Vector3.ClampMagnitude(cohesion, maxSpeed);
        if (separationCount > 0)
        {
            separation = separation / separationCount;
            separation = Vector3.ClampMagnitude(separation, maxSpeed);
        }
        alignment = alignment / boids.Length;
        alignment = Vector3.ClampMagnitude(alignment, maxSpeed);

        velocity += cohesion + separation * 10 + alignment * 1.5f;
        velocity = Vector3.ClampMagnitude(velocity, maxSpeed);
    }

    void Update()
    {
        if (transform.position.magnitude > 25)
        {
            velocity += -transform.position.normalized;
        }

        transform.position += velocity * Time.deltaTime;

        Debug.DrawRay(transform.position, separation, Color.green);
        Debug.DrawRay(transform.position, cohesion, Color.magenta);
        Debug.DrawRay(transform.position, alignment, Color.blue);
    }
}

我现在添加了这部分用于检查,但boid永远不会为空:

if (boid == null)
                    print("It's null !!!!!");

null异常就行了:

alignment += boid.GetComponent<BoidFlocking>().velocity;

我有5个球体,附有相同的脚本,Velocity全部设置为X = 1 Y = 1 Z = 1

我试着在这里学习教程:

Boid and birds in Unity3D

但我无法弄清楚为什么我会得到null异常。

1 个答案:

答案 0 :(得分:2)

如果无效则无效,那么就这样写:

alignment += boid?.GetComponent<BoidFlocking>()?.velocity ?? Vector3.zero;

此行说明,如果boidGetComponent<BoidFlocking>()为空,则使用Vector3.zero作为默认值。