当前位置:网站首页>Singleton mode in unity
Singleton mode in unity
2022-06-30 04:57:00 【LintonL】
Encountered a hole in the simplest singleton pattern ... Here is a record of , In case you forget again
General single thread singleton mode , You can use common methods or attributes to implement global access points , Here, I use the public method
/// <summary>
/// Implementation of single thread and single instance mode
/// </summary>
public class Singleton
{
// Define a static variable to hold the instance of the class
private static Singleton uniqueInstance;
// Constructor private , Prevent the outside world from creating such instances
private Singleton()
{
}
/// <summary>
/// Defining a public method provides a global access point , You can also define public properties to provide global access points
/// </summary>
/// <returns></returns>
public static Singleton GetInstance()
{
// Determine whether class instances exist , Create if it does not exist , Otherwise go straight back to
if (uniqueInstance == null)
{
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}If you want to support multi-threaded access , Then add the thread lock in the method of obtaining the instance (lock), The specific code will not be written
And then say , The problem I have
/// <summary>
/// Implementation of single thread and single instance mode
/// </summary>
public class Singleton :MonoBehaviour
{
// Define a static variable to hold the instance of the class
private static Singleton uniqueInstance;
// Constructor private , Prevent the outside world from creating such instances
private Singleton()
{
}
/// <summary>
/// Defining a public method provides a global access point , You can also define public properties to provide global access points
/// </summary>
/// <returns></returns>
public static Singleton GetInstance()
{
// Determine whether class instances exist , Create if it does not exist , Otherwise go straight back to
if (uniqueInstance == null)
{
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}I wrote a single example , And then inherit from MonoBehaviour, Then there are some data and code , It's not specifically written here , Then the problem is : Every time the data is stored in the dictionary or field of this class , It will become empty the next time it is called .
Pass through the code breakpoints and debug Debugging of , After finding the stored data , The data can be seen and saved , But then call GetInstance() Method to get an instance , The data will be cleared ,uniqueInstance Will turn into null, Even if you are saying uniqueInstance Field time , Instantiate it , It will also become null
What are the specific reasons , I have no definite answer , This problem can only be avoided by debugging , See the big guy know what the reason is , Can also give this dish chicken answer .
I used two methods here , In succession MonoBehaviour Implementation of the singleton
The first one is , Directly in Awake() Method , Then the public method returns the class directly , Why not assign values to public methods , Because static methods cannot be used this keyword
/// <summary>
/// Implementation of single thread and single instance mode
/// </summary>
public class Singleton :MonoBehaviour
{
// Define a static variable to hold the instance of the class
private static Singleton uniqueInstance;
// Constructor private , Prevent the outside world from creating such instances
private Singleton()
{
}
private void Awake()
{
uniqueInstance = this;
}
/// <summary>
/// Defining a public method provides a global access point , You can also define public properties to provide global access points
/// </summary>
/// <returns></returns>
public static Singleton GetInstance()
{
return uniqueInstance;
}
}The second is to modify the processing when the instance is empty , It's no longer new new One , Instead, look in the scene , Add if not , Then return the found result or the added script
/// <summary>
/// Implementation of single thread and single instance mode
/// </summary>
public class Singleton :MonoBehaviour
{
// Define a static variable to hold the instance of the class
private static Singleton uniqueInstance;
// Constructor private , Prevent the outside world from creating such instances
private Singleton()
{
}
/// <summary>
/// Defining a public method provides a global access point , You can also define public properties to provide global access points
/// </summary>
/// <returns></returns>
public static Singleton GetInstance()
{
if (uniqueInstance== null)
{
// If uniqueInstance It's empty , Just look for instances of this class in the scenario
uniqueInstance= FindObjectOfType(typeof(Singleton)) as Singleton;
// If uniqueInstance It's still empty , Just create an empty object and add this class
if (uniqueInstance== null)
{
GameObject obj = new GameObject();
uniqueInstance= obj.AddComponent<Singleton>();
}
}
return uniqueInstance;
}
}Guess from two solutions above ,unity Hang on the class instantiated by the script , And direct new The classes are different , Cannot recognize each other
边栏推荐
- The difference between SVG and canvas
- Under what conditions does the Z-index attribute expire?
- Free travel recommendation in Bangkok: introduction to the Mekong River in Bangkok
- Introduction to some representations, neighbors and degrees of Graphs
- Unity enables simple music visualization
- Photon pun refresh hall room list
- Approaching history, introduction to the London Guard Museum
- How to apply for SSL certificate from the manufacturer
- 【Paper】2015_ Active fault-tolerant control system design with trajectory re-planning against actuator
- Passing values between classes using delegates and events
猜你喜欢

Pourquoi l'ordinateur n'a - t - il pas de réseau après l'ouverture du Hotspot win10?

Unreal 4 learning notes - data storage using blueprints

harbor api 2.0查询

Recommended cultural landmarks of these tourist attractions in Bangkok

力扣27. 移除元素

Winter vacation parent-child tour, these new york attractions are not only fun but also knowledge

Singapore parent-child tour, these popular attractions must be arranged

【Paper】2015_ Active fault-tolerant control system design with trajectory re-planning against actuator
![[UGV] schematic diagram of UGV version 32](/img/4b/03471d2cc96be5d57c97fd1c4e17dc.jpg)
[UGV] schematic diagram of UGV version 32

Have a heart beating Valentine's day in Singapore
随机推荐
How to renew an SSL certificate
Spring Festival Tourism Strategy: welcome the new year in Bangkok, Thailand
Redis cluster concept
Arsenal Stadium Tour - take you to the front and back of Arsenal Stadium
Arrays class
Royal Albert Hall, a popular landmark in London
【Paper】2019_ Distributed Cooperative Control of a High-speed Train
Solution to the 292 week match of Li Kou
Photon pun refresh hall room list
C # equipment synthesis
Li Kou 2049: count the number of nodes with the highest score
Passing values between classes using delegates and events
Force buckle 704 Binary search
Unity3d realizes Google Digital Earth
Singapore must visit these scenic spots during the Spring Festival
0 basic unity course. Bricklaying
National Museum of Singapore - give you spiritual and physical satisfaction
【Paper】2015_ Active fault-tolerant control system design with trajectory re-planning against actuator
Unity ontriggerenter does not call
Oculus quest2 development: (I) basic environment construction and guide package