Home > database >  Put Components into a list or array?
Put Components into a list or array?

Time:01-04

how can I collect the name of all of my Script(Generic) (in a list or array?) Like below?

public class inputdata
    {
        public Component com;
        public int index;

        public inputdata(Component newcom,int newindex)
        {
            com = newcom;
            index = newindex;
        }
    }
inputdata[] data = {new inputdata(component1, 1),inputdata(component2, 1),inputdata(component3, 1)}

foreach (inputdata ft in data)
{
movefunc <ft.com> (ft.index);
}


void movefunc <T> (int index){
  gameobject.GetComponent<T>()
}

it 's shows 'component1' is a type, which is not valid in the given context.

component1 is my c# script, I use it for detecting raycast.

like this

hitInfo.collider.gameObject.GetComponent <component1 > ()

CodePudding user response:

It seems not clear what you are trying to achieve. In case it helps you can achive a list of the components in a gameObject like this:

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

public class GetComponets : MonoBehaviour {
    public GameObject goWithComponets; //attach in the inspector

    void Start() {
        getComponets().ToList().ForEach(component => {
            Debug.Log(component.GetType().ToString());
        });
    }

    private IEnumerable<Component> getComponets() {
        return goWithComponets.GetComponents<Component>().ToList(); ;  
    }
}

Your components wont be generic, they for sure will inherit from the Component type, so in case its needed you can grab all the components from the gameObject getting all the components from the base class Component, and if you need to handle specifics types, handle that later on with some code.

CodePudding user response:

Sounds to me like you don't want a generic but rather something like e.g

public class inputdata
{
    public Type Type;
    public int Index;

    public inputdata(Type type, int index)
    {
        Type = type;
        Index = index;
    }
}

inputdata[] data = new []
{
    new inputdata(typeof(component1), 1),
    new inputdata(typeof(component2), 1),
    new inputdata(typeof(component3), 1)
};

and then

foreach (inputdata ft in data)
{
    movefunc (ft.type, ft.index);
}

and

void movefunc (Type type, int index)
{
    // ... whatever happens before and where you get the hitInfo from

    if(hitInfo.collider.TryGetComponent(type, out var component))
    {
        // component of given type exists on the hit object
        // "component" will contain a reference to it in the base type "Component" -> if you need it in its actual type you will need to cast
    }
    else
    {
        // there is no component of given type on the hit object
    }
}
  •  Tags:  
  • Related