1

How do I assign a gameObject of one script through another script's gameObject? For example; Script_1

public class Script_1 : MonoBehaviour
{
    public OVRScript OVR;
}

Script_2

public class Script_2 : MonoBehaviour
{
    private Script_1 src_1;
    public GameObject Front;

  void Start()
    {
        src_1 = (Script_1) GameObject.FindObjectOfType(typeof(Script_1));
        src_1.GetComponent<OVRScript >().OVR = Front //I am facing problem here
    }

}

Both GameObjects "OVR" and "Front" contain the OVRScript

  • Does this answer your question? [How to access a variable from another script in another gameobject through GetComponent?](https://stackoverflow.com/questions/26551575/how-to-access-a-variable-from-another-script-in-another-gameobject-through-getco) – Ruzihm Mar 18 '20 at 15:44

2 Answers2

1
src_1.GetComponent<OVRScript>().OVR = Front.GetComponent<OVRScript>().OVR;
Ben Rubin
  • 6,909
  • 7
  • 35
  • 82
0

I don't know or see the OVRScript class but isn't OVR rather a member of Script_1?

And then you would want to use GetComponent on the Front in order to get a component attached to it.

// If possible rather drag your Script_1 in here directly via the Inspector
[SeializeField] private Script_1 src_1;

void Start()
{
    // Now I would use find only as fallback
    if(!scr_1) src_1 = GameObject.FindObjectOfType<Script_1>();

    // then you want to assign the OVR field of the 'src_1' of type 'Script_1'
    // and not use 'src_1.GetComponent<OVRScript>()' which would return
    // the reference of an 'OVRScript' component attached to the same GameObject as the Script_1
    //
    // And you want to fill it with the reference of an 'OVRScript' attached to 'Front'
    src_1.OVR = Front.GetComponent<OVRScript>();
}

(see [SerializeField])


It would be even better if you directly define

public OVRScript Front;

now if you drag in a GameObject it a) is checked if this GameObject actually has a OVRScript attached, otherwise you can't drop it and b) instead of the GameObject reference already the OVRScript reference is serialized and stored so there is no need for GetComponent anymore:

[SeializeField] private Script_1 src_1;
public OVRScript Front;

void Start()
{
    // Now I would use find only as fallback
    if(!scr_1) src_1 = GameObject.FindObjectOfType<Script_1>();

    src_1.OVR = Front;
}
derHugo
  • 83,094
  • 9
  • 75
  • 115