GetComponent not recognising component in Unity JavaScript code

戏子无情 提交于 2019-12-24 08:00:54

问题


I have a code block that starts a timer, enables a script, instantiates, then disables that script (this makes my game mechanic work out). The only issue I'm facing now is my Javascript code isn't recognising a component (triggered) error reads script as undeclared from the public variable (which has been added, and which holds the script).

I followed the example that Unity had, and that didn't seem to work out. Any help is appreciated. Here is my code:

#pragma strict

var enemy : Transform;
private var timer : float;
public var mother : GameObject;

function Awake() {
    timer = Time.time + 14;
    script = mother.GetComponent(triggered);
    script.enabled = script.enabled;
}

function Update() {
    if (timer < Time.time) {
        Instantiate(enemy, transform.position, transform.rotation);
        timer = Time.time + Random.Range(55, 60);
        script.enabled = !script.enabled;
    }
}

回答1:


The script variable is not declared.

#pragma strict

var enemy : Transform;
private var timer : float;
public var mother : GameObject;

//DECLARE IT
private var script : triggered;

function Awake() {
    timer = Time.time + 14;
    script = mother.GetComponent(triggered);
    script.enabled = script.enabled;
}

function Update() {
    if (timer < Time.time) {
        Instantiate(enemy, transform.position, transform.rotation);
        timer = Time.time + Random.Range(55, 60);
        script.enabled = !script.enabled;
    }
}

Note:

Please learn C# and start using it in Unity. You will save yourself your time. Also, when creating scripts make sure to capitalize them. For example, triggered should be Triggered.



来源:https://stackoverflow.com/questions/45522630/getcomponent-not-recognising-component-in-unity-javascript-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!