"this" is not valid in a static property, static method, or static field initializer ERROR !!!!

hey everbody, i have an error and error code’s = error CS0026: Keyword `this’ is not valid in a static property, static method, or static field

This is my health codes in my player script.

[System.Serializable]
    public class PlayerStats
    {
        public float Health = 100f;
    }

    public static PlayerStats playerStats = new PlayerStats();

    public static void DamagePlayer (int damage)
    {
        playerStats.Health -= damage;
        if(playerStats.Health <= 0)
        {
            GameMaster.KillPlayer(this);
        }
    }

This is Damage code in my enemy script.

private void OnTriggerEnter2D(Collider2D other)
    {

        if (other.gameObject.tag == "Player")
        {
            Destroy(gameObject);
            BoolFalser.isCreatedsag = false;
            BoolFalser.isCreatedsol = false;
            NewDamage();
        }
    }

    void NewDamage()
    {
        Player.DamagePlayer(hasar);
    }

i have already told u , i have an error . This is my error = error CS0026: Keyword `this’ is not valid in a static property, static method, or static field

i searched on internet , i found i cant use “this” code in static method . I dont understand clearly, please helpme ?

by the way sorry about my english , im not good at writing :slight_smile:

oo sorry i forget add my gamemaster script :slight_smile:

this is my gamemaster script ( it means kill player or kill enemy )

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameMaster : MonoBehaviour {

    public GameObject Deletable;
    public GameObject Deletable2;

    public static void KillPlayer(Player player)
    {
        Destroy(player.gameObject);
    }

    public static void KillEnemy(Enemy enemy)
    {
        Destroy(enemy.gameObject);
    }

    private void OnBecameInvisible()
    {
        Destroy(Deletable);
        Destroy(Deletable2);
    }
}

‘this’ refers to an instance of the class. Static methods have no instances, so ‘this’ is not valid.

1 Like

i understand i cant use "this " okey , but how can i fix ? any idea ? i need help :slight_smile:

If you just are asking why you can’t use the word this, it’s because “this” refers to an instance of a class.

public class AClass
{
   public static void DoSomething()
   {
      this.gameobject....
   }
}

For example DoSomething is called on the class itself.

AClass.DoSomething();

Which means it’s not on an instance of that class, so it can’t reference “this”.

To fix it, don’t use a static method. Or you have to pass in a reference to your target and replace “this” with that reference. Or you have a static variable that references the player and you kill that off.

2 Likes

A proper fix incudes to not mis-use the static keyword. “Player” is a certainly an entity that literally demands individual instances, even if there’s ever going to be just a single one. Avoid modelling objects the way you did. *Fun fact below.

That is, remove the static keyword, access the player instance directly and call its instance methods.
You already compare the tag of the object you collided with, use GetComponent on that GameObject to get the player component.

*Fun fact:
I’ve recently read interesting discussions about absolute OOP environments: Some people insist on not having statics/static state at all, and instead, everything should be modelled in a way that it can be instantiated.

I don’t share that opinion tho, I’d miss my handy utils and the like. :roll_eyes:

3 Likes

There is a valid argument that everything with state should be instantiated. I don’t fully adhere to it, but its a valid argument.

I don’t think I’ve ever heard a valid argument for requiring instances for inherently stateless functions.

Wouldn’t you just use singletons in that situation?

I mean, you very often need initialization of some kind anyway, either to pull things in from the game engine or just to calculate some constants based on some properties.

I am not a good enough formal programmer to fully appreciate the greater implications of completely eschewing static classes.

What I can say, is that I aint got time for none of that. If you’re an independent game developer, you just plain shouldn’t worry that much about an architecture feature that trivial. Sith deal in absolutes!

Watch out for bloat though. That’s the one thing I will say about static classes, they like to feature creep over the single-responsibility principle and create dependencies. That and you can’t use inheritance.

All of the following could be considered Off Topic.

It’s indeed a valid argument, that’s true.
They refer to the real world, in which everything has some kind of state and can be an object. Everything is done based on instances [of something]. It’s just the way we look at it, we do abstract a lot of things. Abstraction is the keyword, as we only take properties into account that we find important and try to combine things the way we need it.

In those conversations, it’s been mentionend that Utility classes are not proper OO, which is also actually true if you consider everything to be an object in an absolute OO environment (even if it doesn’t make much sense to do that).

It’s just a way we look at it. :slight_smile:
I’m not trying to convince anyone though, it’s just that I found these conversations extremely interesting, just like probably anything related to programming, software architecture/design/engineering. :smile:

After all that’s just one way you can look at it and deal with certain requirements, just one of several solutions.
Pros and cons everywhere, even the Gang of Four recognized and agreed (after all the criticism) that’s it’s not the best thing they had come up with.

statics are just a trade-off in a true OO system. in reality not everything needs to be abstracted, encapsulated,composited, or polymorphic. you can certainly try, but its needless work. think about Mathf for example. technically you could make it a generic, abstract class and then make one instance work on floats, and another for vectors, and so on. but thats alot more work which very likely won’t see much exploitation… and then theres the matter of every class needed to inject a reference just to use it. Thats a lot of hoops to jump through.

Enter statics, a concept of no instances, there’s just the concept itself which you can use it immediately. Its not true to OOP so using it recklessly can make an architecture messy real fast (I know this all too well after picking up after someone), but it does reduce the burden on the things you don’t plan on making more complex. as said before they are a trade-off and the key is knowing when to use them effectively.

Theres a reason why true OO systems are so rare. They’re straight up a pain in the ass to develop correctly.

2 Likes