accessing a variable called force from another script

I’m trying to access a variable called force from another script. I have a weapon behavior script called “WeaponBehavior” which has a force variable. this what i was trying to do. the weapon behavior script is not on the same game object as the script below.
part of the script below. I am using C#, but can translate if you know JS.

void FRBodyShot()
	{
		//if(hit.collider.SendMessageUpwards("force")SendMessageOptions.DontRequireReceiver)

		if(force > 100)
	
		{
			animation.CrossFade("fallBack");
			//yield WaitForSeconds(Random.Range(5,30));
			//yield WaitForSeconds(Random.Range(3,30));
		}
			
			else
			{
				animation.CrossFade("hit1");
				//yield WaitForSeconds(Random.Range(2,5);
			}
			
		
	}

Please search if there is another related question before posting yours. There are hundreds of this one, and hundreds of solutions with them.

2 Answers

2

General format is to call GetComponent on the other GameObject, this will return an instance of that component (including scripts) if found.

GameObject someGameObject = GameObject.Find("SomeObjectName");
SomeScriptName someScript = someGameObject.GetComponent<SomeScriptName>();
Float force = someScript.force;

The script reference doesn’t have a code example for C#, but it could help. ScriptReference

How you would do it is.

1- In this script set a reference for the other script and set a reference for the other gameObject;

          GameObject otherGameObject;
          otherScriptName oSN;

2- In Awake() find the other gameObject

      void Awake(){
           otherGameObject = GameObject.FindGameObjectWithTag("otherGameObjectsTag");

3- then, in the function you are calling force from get the script and force value

     void FRBodyShot() {
          oSN = (otherScriptName)otherGameObject.GetComponent("otherScriptName");

4- Now use the script reference to access force

          void FRBodyShot() {

               oSN = (otherScriptName)otherGameObject.GetComponent("otherScriptName"); 
                    
               if(oSN.force > 100)
                    animation.CrossFade("fallBack");
               else
                    animation.CrossFade("hit1");

          }

And… there you have it!

Hope that helps!
A.