system
1
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*.name)*
_ return Images*.sprite;_
_ }_
_ return null;_
_ }_
_}*_
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*.name)*
return Images*.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.
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.