首页 > 解决方案 > 即使游戏对象被禁用,也让脚本修改变换位置

问题描述

我正在尝试使用主摄像机位置来显示和消失。例如,如果camera.main.transform.position = (0,2,0);使对象出现,否则使其消失。

本例中的对象是基本的Cube. 我开始使用setActive函数,但事实证明,一旦你拥有特定对象上setActivefalse, Update函数,它就不会运行。我添加了我正在使用的脚本:

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

public class backandforth : MonoBehaviour
{

    public float speed = 2.5f;
    GameObject targetObject;

    // Use this for initialization
    void Start()
    {
        targetObject = GameObject.Find("Cube");
        targetObject.SetActive(false);
    }

    // Update is called once per frame
    void Update()
    {
        //move the cube from (0,0,0)
        if (Camera.main.transform.position== new Vector3(0, 2, 0)) { 
            transform.position = new Vector3(Mathf.PingPong(Time.time * speed, 5), transform.position.y, transform.position.z);
            transform.Rotate(0, 0, 5);
        }
        else
        {
            targetObject.SetActive(true);
            transform.position = new Vector3(Mathf.PingPong(Time.time * speed, 5), transform.position.y, transform.position.z);
            transform.Rotate(0, 0, 100);
            //gameObject.SetActive(false);
        }

    }
}

这是设置的层次结构视图,以使游戏对象定义清晰。 在此处输入图像描述

关于我该如何做这件事的任何建议?谢谢!

标签: c#unity3d

解决方案


如果我理解正确,更新方法应该是这样的:

void Update()
{
    if (Camera.main.transform.position== new Vector3(0, 2, 0)) {
        //if the camera.main.transform.position = (0,2,0); make the object appear
        targetObject.SetActive(true);
    }
    else
    {
        //otherwise make it disappear
        targetObject.SetActive(false);
    }

}

推荐阅读