父对象不访问子脚本中的变量

Parent object not accessing variables from children's script

我正在使用 Unity 开发一个项目,我创建了一个名为 DeerHater 的脚本,它针对进入指定区域的对象的变换和控制器。该脚本本身可以工作,但它连接到一个父对象,该对象附有它的控制器,并且该控制器应该访问 DeerHater 的变量,然后执行指定的功能。

问题是控制器中的变量没有从空变量变为 DeerHater 中自所需对象进入触发器以来已更改的变量,它显示了以下两个错误:

NullReferenceException: 对象引用未设置到对象的实例

缺少字段异常:DeerController.targetDeer

我完全看不出问题出在哪里,因为我是一个初学者,谁能告诉我为什么它不能访问 DeerHater 变量?

BearController 脚本(父对象):

var distanceDeer : float;
var deerHater : DeerHater;
var deer : GameObject = null;
var targetDeer : Transform;
var isFollowing : boolean = false;
var center : Transform;

var deerKilled : boolean = false;

function Start()
{
    deerHater = GameObject.Find("DeerHater").GetComponent(DeerHater);
}

function Update()
{
    deer = deerHater.deerController.
    targetDeer = deerHater.stupidDeer;
    distanceDeer = Vector3.Distance(deerHater.stupidDeer.position, transform.position);

if(deerHater.collisionDeer == true)
    {
        ChaseDeer();
        if(distanceDeer < attackRange)
        {
            deer.health = -0.1;
            deerKilled = true;
        }

        if(deerKilled == true)
        {
            GoBack();
            deerKilled = false;
        }
    }
}

function ChaseDeer()
{
    var rotation = Quaternion.LookRotation(deerHater.stupidDeer.position - transform.position);
    transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
    moveSpeed = 6;
    animation.Play("Run");
    animation["Run"].speed = 1.25;
    moveDirection = transform.forward;
    moveDirection *= moveSpeed;
    isFollowing = true;

    moveDirection.y -= gravity * Time.deltaTime;    
    controller.Move(moveDirection * Time.deltaTime);
}

这是 DeerHater 脚本:

#pragma strict

var stupidDeer : Transform;
var deerController : DeerController;

public var collisionDeer : boolean = false;

function OnTriggerEnter(col : Collider)
{
    if(col.gameObject.tag == "Deer")
    {
        collisionDeer = true;
        stupidDeer = col.gameObject.transform;
        deerController = col.gameObject.GetComponent(DeerController);
    }
}

function OnTriggerExit(col : Collider) 
{
    if(col.gameObject.tag == "Deer")
    {
        collisionDeer = false;
        stupidDeer = null;
        deerController = null;
    }
}

提前致谢!

我设法通过将 DeerHater 代码放入 BeerController 并将鹿变量从全局变量移动到 if(deerCollision == true) 来解决此问题。