iLMS知識社群歷程檔登入
位置: 黃國哲 > Unity
1090408 控制或關閉腳本Script
by 黃國哲 2020-04-08 10:38:42, 回應(0), 人氣(700)



GameObject.Find("ObjectName").GetComponent<scriptName>().enabled=true/false;



以下有兩個腳本,分別為Light和Test03

代碼:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

 

public class LightEnabled : MonoBehaviour

{

    private Light mylight;

    private Test03 scri;

 

    // Start is called before the first frame update

    void Start()

    {

        mylight = GetComponent<Light>();

        scri = GetComponent<Test03>();

    }

 

    // Update is called once per frame

    void Update()

    {

        if (Input.GetKeyUp(KeyCode.Space))

        {

            //mylight.enabled = false;

            //關閉腳本,這裡是關閉燈光,燈光類似於元件前面勾選狀態控制

            mylight.enabled = !mylight.enabled;

            //!的意思是 前面的值取反當為true時候結果為false

            scri.enabled = !scri.enabled;

            //腳本開關狀態切換

 

            //GameObject.Find("Directional Light").GetComponent<Test03>().enabled = !GameObject.Find("Directional Light").GetComponent<Test03>().enabled;

            ////隱藏腳本第二種寫法

 

 

        }

    }

回應