Home > other >  how to change variable through interface inheritance?
how to change variable through interface inheritance?

Time:08-30

i want each projectile in my game to contain a bool saying if its the player's or not

public interface projectile
{
    public bool isPlayers { get; set; }
}

public class Bullet : MonoBehaviour, projectile
{
    public bool isPlayers { get { return (_isPlayers); } set { _isPlayers = value; } }
    private bool _isPlayers;
}

when any weapon fires i check if it was by the player or not and set it accordingly

public class Cannon : MonoBehaviour, Iaweapon
{ 
    ...
    public void Attack()
    {
        ...
            if(transform.parent.tag == "Player")
            {
                prefab.GetComponent<projectile>().isPlayers = true;
            }
        ...
    }
}

but when debugging the bool is not set to true

CodePudding user response:

Your class does not implement your interface.

In order to do it you will have to add it as you did for Iaweapon interface.

 public class Cannon : MonoBehaviour, Iaweapon,  projectile
{ 
    ...
    public void Attack()
    {

Also in order for you to be able to recognise easier your different types such as interfaces I recommend you putting an "I" before all of you your interface names. It will make your life easier.

CodePudding user response:

Given the varialbe names, I'm going to assume that you're checking a 'prefab' instead of an instantiated object. With that in mind, your code should look something more like this:

public interface IProjectile
{
    bool isPlayers { get; set; }
}


public class Bullet : MonoBehaviour, IProjectile
{
    ...
    public bool isPlayers { get; set; }
}


public class Cannon : MonoBehaviour, IWeapon
{
    [SerializeField] private GameObject prefab;
    ...
    public void Attack()
    {
        ...
        var instance = Instantiate ( prefab );
        var component = instance.GetComponent<IProjectile>( );
        if ( component != null )
            component.isPlayers = transform.parent.CompareTag( "Player" );
        ...
    }
}
  • Related