Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

c# - How do I properly call banner if I get warning for using monobehaviour like I added in description


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You shooukd not create monobehaviour or derived classes with new. Take into accounr that even if the language used in unity is c# there some special thinngs that need to be taken into account. For exmple monobehaviour class doesn't support the null-conditional operator (?.) and the null-coalescing operator (??). Check the docs

Another important thing of monobehaviours is that the "live" inside gameobjects. This is how the unity engine operates and the class is designed to be used as gameObject component. This means that you cannot make a Monobehaviour myMB = new Monobehaviour() wherever you wish in the code and make your logic. Instead yo should do:

GameObject myGO = new GameObject;
Monobehaviour myMB = myGO.AddComponent<Monobehaviour>();

This has the consequence that if you need to use a monobehaviour for anything, you need to have the corresponding gameObject in the scene for this, which sometimes you wont specifically need, apart from the need of handling the monobehaviour itself. This sometimes might seem not as neat or clean as it could have been for your app, but many times there are workarounds to avoid the gameObject creation if you make the effort, but most of the times you start the avoiding the corresponding gameobject creation journey, you end up finally creating it because to avoid it does not make sense.

So to sum up, take into accout that to use any monobehaviour yo need the corresponding gameobject for it to live in. You can try check the docs for better undestanding.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...