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

时间:2015-03-05 09:01:41

标签: unity3d triggers artificial-intelligence unityscript

我正在Unity中开展项目,我创建了一个名为DeerHater的脚本,该脚本以进入指定区域的对象的变换和控制器为目标。该脚本本身可以工作,但它连接到一个父对象,该对象附加了控制器,该控制器应该访问DeerHater的变量,然后执行指定的函数。

问题是控制器中的变量不会从空变为DeerHater中已更改的变量,因为所需的对象进入了触发器并且它显示了这两个错误:

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

MissingFieldException: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;
    }
}

提前致谢!

1 个答案:

答案 0 :(得分:0)

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