简体   繁体   中英

Generic method in Unity3d

Hello dear developers and engineers! I stumbled upon the usage of a generic method. I don't have to use generic. However, I preferred it. I use Unity3D. MageAA class has access to EnemyID class and Player controller class. PlayerController class has no access to others. My point is to create a generic method in PlayerController class. Then call that method in MageAA with EnemyID as an argument. Here what I've. How can I make it work? Thank you!

public class MageAA : MonoBehaviour
{
    public GameObject selectedTarget;

    PlayerController controller;

    // Start is called before the first frame update
    void Awake()
    {
        controller = GetComponent<PlayerController>();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        selectedTarget = controller.SelectPointedObject<EnemyID>();
    } 
}



public class PlayerController : MonoBehaviour
{
    public GameObject SelectPointedObject<T>() where T: class
    {
        if(Input.GetKeyDown(KeyCode.Mouse0))
        {
            RaycastHit[] hits = RaycastAllSorted();
            
            if (hits.Length > 0 && hits[0].transform.GetComponent<T>() != null)
            {   
                return hits[0].collider.gameObject;
            }
            else
            {
                return null;
            }
        }
        return null;
    }
public interface ICharacter 
{ 
    public string Name { get; set; }

    public int Health { get; set; }
}
public class Character : ICharacter
{
    public string Name { get;set; }
    public int Health { get; set; }

    public string GetOrSetName(string name) 
    {   
        if (Name != null)
            Name = name;
        return Name;
    }
}

public class Hero : Character
{
    public string Name { get; set; }
    public int Health { get; set; }
}
public class NPC : Character
{
    public string Name { get; set; }
    public string Role { get; set; }
}
public class NamerClass
{   
        public Character Character { get; set; }
    
        public string GetOrSetName<T>(string text)  where T :  Character, new ()
        {
            return Character.GetOrSetName(text);
            
        }
}
static void Main(string[] args)
        {
Hero hero = new Hero();
            NPC npc = new NPC();
            
            NamerClass genericNamer = new NamerClass();

            genericNamer.GetOrSetName<Hero>("SUPER MARIO");

            genericNamer.GetOrSetName<NPC>("POTION MARKET");
}

"May be this gives you an idea"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM