Trying to access a function/method from another C# script

Ok, so I got a problem that im trying to figure out being a newbie and all. If I write a script to make the camera shake when space ship is hit- How can I access the method called Shake() from a script called ShakerScript and call it from my EnemyScript so once my player gets hit after the Attack() method is called in the latter script- the screen will shake a bit… how do I do that? Again, I dont need help with the Shake() method in the ShakerScript, I just need help to call it in the EnemyScript.

Thanks aga

The way i currently know how to do this is: in the script you want to call the shake method, create a variable GameObject and name it, then give it a value in awake or start something like, GameObject.Find(“Name of game object”).GetComponent();

Then you can use the variable name.Shake(), i think shake will need to be a public function as well.

I don’t know if there is a better way, but this is the only way i currently know how to do this.

Ok so I call it

public GameObject shaking;

void Awake
{
GameObject.Find("shaking").GetComponent<CameraShake>();
}

void Update
{
shaking.Shake();
}

However when I get to that line of shaking.Shake(); my intellisense will not go past shaking. so something is not right. Any suggestions? :slight_smile:

And yes this script is on the Camera object in my hierarchy.

You are trying to call the function ‘shaking’ on the GameObject, not the script.

Ok Im confuse how would you write it if the method im calling from the other script is Shake();
lol :slight_smile: im such a newbie lol

What you need to do is get the script component first and then call the function.

ShakerScript script;
void Start()
{
script=GameObject.Find("shaking").GetComponent<ShakerScript>();
}

//call using script.Shake();

Thanks that helped that intellisense was able to finish the script.Shake(); but still have to findout why the script is not executing the shake. Thanks again- i think Im on the right track.

Ok I got it working… that “shaking” was name of tag on my camera! I was like Doh! Im such a noob… now my camera shakes when my object crashes into an object!!! Yay! Thanks aot Random_Civilian and thank you as well SteveJacobs90 for contributing also.