#How to acess script from another GameObject. I tried and got the GameObject but i couldnt get script

1 messages · Page 1 of 1 (latest)

lavish prism
#

i was trying to acess a script from another gameobject . First i grab the gameobject using GameObject.Find(GameobjectName); and i could get that and as next step i try to grab the script attached to the GameObject and i couldint get it , and i was trying to get it like this variableName=GameObjectName.GetComponent<scriptName>();
and i am getting null,
can any one help . Thanks

true sonnet
#

you can try adding a public variable for the gameobject's script.
smth like this:
public "YourScriptName" "nickname"

then to access it, you can use smth like this:
"nickname"."thing you wanna access

I'm not entirely sure if this would work but this helped me with one of my things before

lavish prism
lavish prism
unreal swift
#

i think youre doing it bit wrong

//decleare something here in this case your script
//declare public, yourScript.cs, your scripts nickname in this script
public FiringScript fireScript;

private void Start(){

  // nickname, getting compoment of<> when object is active
  fireScript = GetComponent<FireScript>();
}

private void Update(){
  
  // if spesific key get pressed 
  if (Input.GetKeyUp("space"))
        {
            // run method from FiringScript of Shoot();
            fireScript.Shoot();
        }
  
}

#

then dont forget to put the script through inspector

lavish prism
ripe eagle
#

@lavish prism Using Find methods to reference a GameObject is wrong. Don't use Find methods. They are slow, unreliable and especially Find itself is also string dependent.

Rather get a direct reference to the component you're searching for through the inspector (drag and drop it into the field that appears in the inspector):

[SerializeField] private YourComponent example; // Drag and drop reference through the inspector

If this isn't possible, because one of the two objects (either the one searching for the reference or the component you want to reference itself) is getting instantiated later on, this direct reference is not possible, as the object doesn't exist yet until you actually run the game and the moment comes to instantiate the object. There are still other ways than Find methods though. You can visit my blog post on this topic, which briefly explains why Find methods are bad and introduces 3 common alternatives: https://duck-dev.github.io/unity/get-a-reference-in-unity/

ripe eagle
#

You're welcome. Did you manage to resolve it?