-1
\$\begingroup\$

There is a float value in my scriptA. And, I'd like to access this float value and change it in scriptB. But, I am getting message that " static member ScripA.float cannot be accessed with instance reference, qualify with type instead. "

My Script A:

using System.Collections; using System.Collections.Generic; using UnityEngine; public class Rectangel : MonoBehaviour { public static float speed = 2; void Start () { } // Update is called once per frame void Update () { } } 

My script 2:

public class script2 : Monobehaviour { public Rectangel rectangle; void Start () { rectangle = GetComponent <Rectangel> (); } void onCollisionEnter2D (Collision2D col) { if (col.gameobject.tag == "Whatever"){ rectangle.speed = 3f; } } } 
\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

Why do you need the speed variable to be static? When you use static it meas you are declaring a member that belongs to the Type itself and not a specific object of that type. So you can go either :

void onCollisionEnter2D(Collision2D col) { if (col.gameobject.tag == "Whatever") { Rectangel.speed = 3f; } } 

Note this will change speed for all objects of type Rectangle. Or you can simply remove the static modifier from the definition of speed and then you will be able to change the speed on a per object basis.

\$\endgroup\$
3
  • \$\begingroup\$ When I remove static, it runs but the value of the speed won't change from 2f to 3f when the player collides with the object having tag "Whatever". \$\endgroup\$ Commented May 4, 2019 at 9:02
  • \$\begingroup\$ Make sure you have the correct reference in rectangle. \$\endgroup\$ Commented May 4, 2019 at 9:09
  • \$\begingroup\$ Yes, I got it working. \$\endgroup\$ Commented May 4, 2019 at 9:29

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.