- Home /
How do I add a float variable into a list ?
Greetings.
I have float variables
public float peso10x, peso50x, peso100x;
And a list
var floats = new List<float> { };
So I want to add these variables into the list in several cases like this
case 1:
Instantiate (peso10, transform.position, Quaternion.identity);
break;
case 2:
Instantiate (peso50, transform.position, Quaternion.identity);
break;
case 3:
Instantiate (peso100, transform.position, Quaternion.identity);
What should I add below the lines with "Instantiate" ?
Thank you very much for help
Answer by ShadyProductions · Sep 01, 2020 at 07:25 AM
Instantiate returns a GameObject, if that's what you want to add you have to store the object returned and add it to the list, but the list must be of type GameObject then not float.
var items = new List<GameObject>();
var item = Instantiate (peso10, transform.position, Quaternion.identity);
items.Add(item);
This is basic C#, not really unity related I'd say.
These questions don't really belong on UnityAnswers.
You need to get a basic understanding of C#.
Actually I am really noob at program$$anonymous$$g :/ I just need to add a float value into the list not the gameobject actually. Can I do that like for example items.Add(floatvariable);
yes but the list must be of type List<float>()
, I don't see the point of this though if you have no understanding of basic C#.
Thank you very much. I am trying to learn :) I will go for the basics after this because of your recommendation.
Answer by imM4TT · Sep 01, 2020 at 01:44 AM
I'm pretty sure you are mixing up C# and JS which isn't a good way to go
, I assume.
Lists in C# are initialized like this : List<float> items = new List<float>();
You can manage them through their method, what you need is items.Add(__floatValue__);
Yep my bad. Thanks to have paid attention to this mistake.
Your answer
Follow this Question
Related Questions
C# Adding Multiple Elements to a List on One Line 5 Answers
NullReferenceException when adding String to list 1 Answer
floats and lists 1 Answer
Pick between two floats 2 Answers
Can I create a list with an int/float and a string? C# 2 Answers