Home > Back-end >  Accessing the variable from another Script on the same GameObject
Accessing the variable from another Script on the same GameObject

Time:10-22

I have a GameObject with script idkhorsey and idkh2.

In idkh2, I'm trying to access a variable of idkhorsey. The variable is a bool called isAlive and I want to print its condition using the Start method of idkh2.

I've tried following tutorials for this but I'm just getting errors. What might I be doing wrong?

The script for 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()
    {
        
    }
}

Thank you.

CodePudding user response:

You can select the gameobject that this script has associated with, having the public variable you will see in the inspector window that you can drag the objects to that variable, drag to that hole the game object . If you don't want to do this you can always search for your object as follows GameObject go = GameObject.Find ("name of your object in the scene") ih = o.GetComponent<idkhorsey>();

CodePudding user response:

idkhorsey ih = go.GetComponent<idkhorsey>();

can not be done in a static context at field declaration.

Rather do it e.g. in

private idkhorsey ih;

private void Awake()
// or
//private void Start()
{
    ih = go.GetComponent<idkhorsey>();
}

Or if you say it is on the same GameObject anyway then why even use go? Simply use

private idkhorsey ih;

private void Awake()
// or
//private void Start()
{
    ih = GetComponent<idkhorsey>();
}

However, way easier would be directly using

public idkhorsey ih;
//or
//[SerializeField] private idkhorsey ih;

and drag your according object into that field directly and forget about go.

  • Related