- Home /
How can i create array of texture2d with variables names ?
Instead doing this:
public Texture2D mouse;
public Texture2D hand;
public Texture2D grab;
To make:
public Texture2D[] cursor;
But also to give already a 3 variables in the script mouse,hand,grab so they will show and i will be able to use them and also that i will be able to add/remove more items from the array.
But how do i make this 3 variables to be already in the array and not empty array ?
Answer by Vicarian · Sep 24, 2017 at 04:40 AM
I don't quite know what you're asking, but it sounds like a struct. You'll be able to serialize a struct to be able to create new fields as you need them:
using UnityEngine;
public class ExampleClass: MonoBehaviour {
[SerializeField] Cursors m_cursors;
[System.Serializable]
struct Cursors {
public Texture2D mouse;
public Texture2D hand;
public Texture2D grab;
}
}
Answer by unit_nick · Sep 24, 2017 at 04:54 AM
Here is how you build a static array
public Texture2D[] cursor = { mouse, hand, grab };
but you can't just add and remove items to an array, you need to create a new array and copy the items you want to keep to the new array.
lists provide similar functionality to arrays but are dynamic and would suit you better?
public List<Texture2D> cursors = new List<Texture2D>();
cursors.Add(mouse);
cursors.Add(hand);
cursors.Add(grab);
cursors.Remove(hand);
you can still access lists like an array
cursors[1] = grab;
Dictionaries are another option
public Dictionary<string, Texture2D> cursors = new Dictionary<string, Texture2D>();
cursors.Add("mouse", mouse);
cursors.Add("hand", hand);
cursors.Add("grab", grab);
cursors.Remove("hand");
and access
Texture2D cursor = cursors["mouse"];
Dictionaries can't be serialized in the Editor, so they aren't necessarily a good option if that's how @Chocolade assigns the cursor textures. Having said that, I doubt it'll be able to serialize a type derived from List that has been given a string indexer. That was my initial thought, but the Editor being unable to serialize it put the stop to that.
Your answer
Follow this Question
Related Questions
How can i make the spaceship to land/take off with physics vertical ? 2 Answers
How can I loop over all vertices and draw triangles ? I'm getting out of range exception 1 Answer
Cannot attach game object to script. 1 Answer
Set default length for an array of elements of a custom class in inspector 0 Answers
How can i Instantiate on the terrain from left to right ? 0 Answers