Unity3D - 禁用状态

时间:2017-03-18 17:49:55

标签: unity3d gameobject

我在游戏对象(此处简化)上有一个脚本组件,在创建时使用testObject.setActive(false)禁用。

using UnityEngine;

public TestObject : MonoBehaviour {
    public int testValue = 5;

    void Start() {
        testValue = 0;
    }

    public int GetTestValue() {
        return testValue;
    }
}

在禁用之前,GetTestValue的返回值为0.一旦我重新启用该对象,返回值为5.

Unity文档说:

  

使GameObject处于非活动状态将禁用每个组件...您附加到GameObject的任何脚本将不再具有调用的Update()...

然而,组件的行为向我表明,脚本制作的MonoBehaviour并未真正被禁用,而是被销毁。如果只有Update()停止被调用,那么它如何解释失去状态?

这里的基本问题是:在不破坏脚本的情况下临时禁用脚本的预期方法是什么?

3 个答案:

答案 0 :(得分:1)

实际发生的是Start()函数仅在对象的生命周期中调用一次。所以在开始时它被调用并将值设置为0.但是当你禁用它并重新激活它时,它就不会被调用。

这并没有改变这样一个事实:即使在停用并重新激活脚本之后,您的值仍然应该相同(正如我们在评论部分中所述)。

使用OnEnable()的一种方法是使用private void OnEnable() { testValue = 0; } ,每次脚本设置为活动时都会调用它。 More info on OnEnable

  

当对象启用并激活时,将调用此函数。

因此,在您的脚本中,您将拥有:

//Test Game Class, Implements the StandardFades
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;

public class TestGame extends Canvas implements Runnable{

private static final long serialVersionUID = -7267473597604645224L;

private Thread thread;
private boolean running = false;
private boolean consoleFPS = true;
private boolean titleFPS = true;

private TestWindow window;

//Fade objects, two is for a really long timer to test to see if they would transition at different times
StandardFade one = new StandardFade(Color.RED,Color.BLUE,.005);
StandardFade two = new StandardFade(Color.RED,Color.GREEN,.00000000000000001);
StandardFade three = new StandardFade(Color.RED,Color.YELLOW,.000005);

private int currentFPS;
private int frames;

public int levelNum;

public TestGame(int width, int height, String title){
    this.window = new TestWindow(width,height, title, this);

    this.initFades();
    this.start();
}

private synchronized void start(){
    if(running)
        return;
    else{
        this.thread = new Thread(this);
        this.thread.start();
        this.running = true;
    }
}

private synchronized void stop(){
    if(!this.running)
        return;
    else{
        try{
            this.thread.join();
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        this.running = false;
        System.exit(0);
    }
}
/**
 * This game loop was provided by online sources, though there are many examples
 * of a game loop online.
 * 
 * @author RealTutsGML
 */
public void run() {
    requestFocus(); //Focuses the click/input on the frame/canvas.
    long lastTime = System.nanoTime(); //The current system's nanotime.
    double ns = 1000000000.0 / 60.0; //Retrieves how many nano-seconds are currently in one tick/update.
    double delta = 0; //How many unprocessed nanoseconds have gone by so far.
    long timer = System.currentTimeMillis();
    int frames = 0; //The frames per second.
    int updates = 0; //The updates per second.
    while (running) {

        boolean renderable = false; //Determines if the game should render the actual graphics.

        long now = System.nanoTime();//At this point, the current system's nanotime once again.
        delta += (now - lastTime) / ns;
        lastTime = now;
        //If the amount of unprocessed ticks is or goes above one...
        //Also determines if the game should update or not/render. Approximately sixty frames per second.
        while (delta >= 1) {
            tick();

            delta--;
            updates++;

            renderable = true;
        }

        if(renderable){
            frames++;
            render();
        }

        if (System.currentTimeMillis() - timer > 1000) {
            timer += 1000;
            System.out.println(frames);
            updates = 0;
            frames = 0;
        }
    }

    this.stop();
}

/**
 * This method should tick everything that needs to be updated via positioning, 
 * mouse input, etc.
 */
private void tick(){
    /********************PUT ALL TICKABLE METHODS IN THIS METHOD; ALL CALCULATIONS, EVERYTHING*********************/
    //this.stdFadeHandler.get(0).tick();

    //this.stdFadeHandler.tick();

    one.tick();
    two.tick();
    three.tick();
    /**********************************END OF TICK METHOD INFORMATION AND METHODS******************************/
}

private void render(){
    BufferStrategy bs = this.getBufferStrategy();

    if(bs == null){
        createBufferStrategy(3);
        return;
    }

    Graphics g = bs.getDrawGraphics();
    Graphics2D g2 = (Graphics2D) g;

    g2.setColor(Color.BLACK);       
    g2.fillRect(0, 0, window.getWidth(), window.getHeight());
    /*******************PLACE ALL DRAWING INSTRUCTIONS WITHIN THIS SECTION OF THE RENDER METHOD*************************/

    g2.setColor(one.getColor());
    g2.fillRect(20, 20, 200, 200);
    g2.setColor(two.getColor());
    g2.fillRect(20, 300, 200, 200);
    g2.setColor(three.getColor());
    g2.fillRect(20, 540, 200, 200);

    //this.stdFadeHandler


    /*******************DO NOT PLACE ANY MORE DRAWING INSTRUCTIONS WITHIN THIS SECTION OF THE RENDER METHOD***************/

    g.dispose();
    g2.dispose();

    bs.show();
}

private void initFades(){


}

public static void main(String[] args){

    TestGame stdGame = new TestGame(800,800,"Test Standard Game");
}

如果您知道此对象将多次激活和停用,并且每次发生这种情况时您都必须执行某些操作。

这让我想到了第二点和我的建议:

不要在要停用和重新激活的脚本上保留重要值。

将重要信息保存在永远不会停用的脚本上,这样,您始终可以确保该值始终是正确的。因此,您并不总是需要重新生成正确的值,并且每次检查它是否真的是您获得的好价值。

答案 1 :(得分:0)

事实证明,问题是竞争条件。在Start()完成之前,TestObject已被停用,这阻止了对象的正确初始化。通过将初始化代码移动到Awake(),对象在停用之前正确设置其状态。

答案 2 :(得分:0)

我有相反的情况..我尝试在 Awake() 中设置动画师参数并立即停用。参数值没有改变。但是如果我把它放在 Start() 中,这个值就被设置了。