-1

I'd like to create a short static function which I could call from everywhere to add into a List of Transform (in Unity), here's what I got:
public class MultipableTargetCamera : MonoBehaviour
{
    public List<Transform> targets;

    public static void AddToCamera(Transform target)
    {
        targets.Add(target);
    }
}

But I get an error message in Unity after saving my script "An object reference is required for the non-static field, method, or property 'MultipableTargetCamera.targets'".

I've tried many things and researched a lot but I can't find any solution that fits my needs.
I want to keep a List of Transform, I dont want use an array or to use a list of strings/ints.

Any ideas?

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
sNNNk
  • 11
  • 5
  • 1
    dont make `AddToCamera` static. – Daniel A. White Sep 22 '20 at 17:42
  • 1
    What daniel said - and don't forget to initialize `targets` before you try to use it... – fredrik Sep 22 '20 at 17:44
  • Thank you it works now, I had the idea of calling my function AddToCamera(...) easily when loading my players that's why I thought of a static function. But now it's ok I just had to find my script by code before executing the function. – sNNNk Sep 22 '20 at 18:06

1 Answers1

2

Your method is static while your field is not. To understand this, ask yourself: Imagine you initialize multiple of these objects, what is the right "targets" list?

Besides of the already commented fact that static can be considered bad practice in this case, the answer is:

You can not access a non-static class member in a static function of that class.

AyJayKay
  • 103
  • 6