- Home /
Help implementing code ;)
Hello! So im currently making SpriteManager, that has Serializable struct, that has sprite and name variables.
Idea is to get sprite by name from every script and i had no problems, but to use function outside i need to make it static, where comes a problem, if i make static function - i should make static List also, but im loosing an opportunity to define struct in the inspector. How can i solve this? Thanks in advance.
using UnityEngine;
using System.Collections.Generic;
public class Image_Manager : MonoBehaviour
{
[System.Serializable]
public struct Image
{
public Sprite sprite;
public string name;
}
//if i make this static i cant define struct in the inspector
public List<Image> Images = new List<Image>();
// Use this for initialization
//If i make this static - i should make a list static
public Sprite GetSpriteByName(string name)
{
for (int i = 0; i < Images.Count; i++)
{
if (name == Images[i].name)
return Images[i].sprite;
}
return null;
}
}
Answer by christoph_r · Nov 24, 2016 at 01:29 AM
Why not use a singleton pattern?
public static Image_Manager instance;
void Start()
{
if (instance != null)
destroy(this);
else
instance = this;
}
You can then access the sprites through the Image_Manager's instance while still having it serializable. By the way, if performance is a concern you might want to generate a Dictionary from your list of images and access the dictionary rather than looping through the list each time. Also, Unity's naming convention is CamelCase for classes and camelCase for fields.
Answer by Desination-X · Nov 24, 2016 at 04:27 AM
What you can do is create a singleton instance.
using UnityEngine;
using System.Collections.Generic;
public class Image_Manager : MonoBehaviour
{
public static Image_Manager singleton;
void Start (){
if(singleton == null){
singleton = this;
} else Destroy(this);
}
[System.Serializable]
public struct Image
{
public Sprite sprite;
public string name;
}
//if i make this static i cant define struct in the inspector
public List<Image> Images = new List<Image>();
// Use this for initialization
//If i make this static - i should make a list static
public Sprite GetSpriteByName(string name)
{
for (int i = 0; i < Images.Count; i++)
{
if (name == Images[i].name)
return Images[i].sprite;
}
return null;
}
}
The only thing is, you can't have more than one Image_Manager in any scene, and if you do have more than one, the latter will destroy itself.
You can now access any public variables using Image_Manager.singleton :)
Hope this answers your question.
Your answer

Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Save static fields values 1 Answer
C# how to setup a Binary Serialization 4 Answers