简体   繁体   中英

Unity3D C#-Pass List value to another class

may I ask about how to pass List value to another class?For example :

using System.Collections.Generic;
public class PassListClass : MonoBehaviour
{
 List<int> passInt=new List<int>();

 public void Start()
 {
  passInt.Add(1);
  passInt.Add(3);
 }

 .
 .
 .
}

So I want to pass 1 and 3 to another class,what should I do after create class instance and call it at another class?I already tried to call the List value to another class but seen not working.Actually I want to pass a list of game object to another class,just trying to get some idea.Thanks for help.

Why not assign it in the new class constructor?

Class1 -> Class2

You could do something like:

Class2 newInstance = new Class2(your_list_from_Class1);

the constructor could be something like:

public Class2(List<something> listToPass){
    this.list = listToPass;
}

I'm not sure I understood your answer completely but I hope I helped. I'm gonna leave here a list of answers that might help you out:

Passing value from one class to another

Passing a list to another class

If both classes are scripts (Extended by MonoBehaviour) then you can't pass a value from Class A into Class B Constructor.

However, what you can do is to either 1. Set the variable you want to pass from Class A -> Class B into a static variable. Then you can just use

Within Class B

 Variable localVariableName;
 public void Update() { 
    if(localVariableName==null)
    localVariableName = ClassA.VariableName; 
 }
 // -- OR if you know that ClassA will run before ClassB --
 public void Start() {
     localVariableName = ClassA.VariableName; 
 }

-- OR -- If you dont want to use a static variable you can find the GameObject that has the ClassA as script and reference to that variable from within Class B

 Variable localVariableName;
 public GameObject OwnerOfClassA;
 public void Start() {
     localVariableName = OwnerOfClassA.GetComponent<ClassA>().VariableName; 
 }

In the Unity3D Editor, just drag the gameobject that owns classA into OwnerOfClassA

I hope this helps!

Cheers, Zerratar.

So this is actually what I do when passing List value to another class.Hope it help.

    public class ListClass : MonoBehaviour
{
  List<int> intList=new List<int>();
  private static ListClass instance;      

  public void Start()
  {
    intList.Add(1);
    intList.Add(2);
    lnstance=this
  }
}

For another class

 public class ValueFromListClass : MonoBehaviour
{
   private ListClass listClass;
   List<int> valueFromListClass=new List<int>();

   public void Start()
   {
     listClass=ListClass.instance;
     valueFromListClass=listClass.intList;
   }
}

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