我有一個帶有腳本idkhorsey和idkh2.
在 中idkh2,我試圖訪問idkhorsey. 該變數是一個名為 bool 的變數isAlive,我想使用 的 Start 方法列印其條件idkh2。
我已經嘗試按照教程進行操作,但我只是遇到了錯誤。我可能做錯了什么?
腳本idkh2:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class idkh2 : MonoBehaviour
{
public GameObject go;
idkhorsey ih = go.GetComponent<idkhorsey>();
// Start is called before the first frame update
void Start()
{
print(ih.isAlive);
}
// Update is called once per frame
void Update()
{
}
}
謝謝你。
uj5u.com熱心網友回復:
您可以選擇與此腳本關聯的游戲物件,擁有您將在檢查器視窗中看到的公共變數,您可以將物件拖動到該變數,將游戲物件拖動到該孔。如果您不想這樣做,您可以隨時按如下方式搜索您的物件
GameObject go = GameObject.Find ("name of your object in the scene") ih = o.GetComponent<idkhorsey>();
uj5u.com熱心網友回復:
idkhorsey ih = go.GetComponent<idkhorsey>();
不能static在欄位宣告的背景關系中完成。
而是這樣做,例如在
private idkhorsey ih;
private void Awake()
// or
//private void Start()
{
ih = go.GetComponent<idkhorsey>();
}
或者,如果您說它無論如何都相同GameObject,那為什么還要使用go?只需使用
private idkhorsey ih;
private void Awake()
// or
//private void Start()
{
ih = GetComponent<idkhorsey>();
}
但是,更簡單的方法是直接使用
public idkhorsey ih;
//or
//[SerializeField] private idkhorsey ih;
并將您的相應物件直接拖到該欄位中并忘記go.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/332867.html
