Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
5
Question by Amaresh · Jul 17, 2014 at 11:35 AM · c#javascriptclassesstruct

Where to use Structs and classes?

Hey Guys! I've made a game which lags on some of the mobile devices. Recently, when I searched for optimisation tips in unity. I came across a UNITE CONFERENCE video on youtube. In this video they suggested that it is better to use structs instead of classes for preventing garbage collection.

I've a lot of scripts in my game and all of them are classes by default. I just want to know where can I use structs and classes.

EDITED : Suppose I've a gameObject with a script (ScriptA) attached to it. And if i'm making a reference to this gameObject via another script(ScriptB).

I this case should I use class or struct for ScriptA?

Thank you.

Comment
Add comment · Show 3
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Tehnique · Jul 17, 2014 at 11:53 AM 1
Share

Usually you use structs for small, immutable objects, like Points for Geometry for example. There are a lot of discussions on this topic on line, you should read a little more on the issue, for example this.

Although structs can contain methods, you shouldn't make structs that contain logic, usually just use them to store an object.

I don't think, though, that your performance issues come from the GC, most likely there are other things at work (draw calls, shadows, view distances, etc).

avatar image Tehnique · Jul 17, 2014 at 12:46 PM 0
Share

For your EDIT: It should be a class, since it requires to be a "Component" in order to put it on an gameObject. Doesn't even matter if you reference it from B or not. It has to be a class in order to inherit Component.

avatar image dinkey007 · Mar 30, 2017 at 10:24 AM 0
Share

1)The structures are value types and the classes are reference types.So object of structure store in stack exactly like any other value type like an Integer, a double but object of class store in heap.Your can assigned null to class variable but you can't assigned null value to structure variable 2)Class support Inheritance but struct does not support so access modifier of a member of a struct cannot be protected or protected internal

3)You can use Destructor in a class but You can use it in a structure

4)When passing a class to a method, it is passed by reference. When passing a struct to a method, it's passed by value ins$$anonymous$$d of as a reference.

5)Structs cannot contain explicit parameterless constructors but You can create in class

like

struct a

{

int result; public b()//it is possible in class, no error will come { result = 5; } }

struct a

{

int result; public b()//it is not possible struct,compile error will come { result = 5; } }

6)You can instance Field initializer of class but You can't do in structs

for example

class emp { public string name = "cheater"; //No synstax error } struct emp { public string name="cheater"; //No synstax error will come }

7)structures can not be garbage collector so no memory management. classes can be garbage collector because garbage collector works on heap memory

credit:- http://tech.queryhome.com/149655/what-is-difference-between-structure-and-class-in-c%23

5 Replies

· Add your reply
  • Sort: 
avatar image
14
Best Answer

Answer by yagizpoyraz · Jul 17, 2014 at 12:09 PM

Hi,

Class is a reference type. If you create an object of that class, variable only holds a reference to memory. Structs on the other hand is a value type. If you create a struct, variable holds the actual value, not a reference to memory. Note that when the struct is assigned to a new variable, it is copied. Changes made to one copy do not affect the other copy.

You can use a struct if you dont need a reference variable. If you need a small data structure that holds a data that you wont modify later, structs are the best.

EDIT (as this is the main answer, I will add my view to this one):

The main difference between both is the way they are passed to methods.

 public class MyClass
 {
       public int valueA, valueB;
 }
 public class MyStruct
 {
      public int valueA, valueB;
 }
 
 void MyMethod(MyClass myClassObject);
 void MyMethod(MyStruct myStructObject);

When passing a class object, the compiler will copy the address value into the parameter which is stored on the method stack. Using the parameter then means to use the actual object as the compiler will jump to the given address location to modify valueA and valueB. Size of myClassObject is 4 bytes.

   myClassObject.valueA = 10;
   myClassObject->valueA = 10; // c++

The c++ way really indicates there is a movement to the value.

 -

When passing the struct object, compiler will copy the entire structure content into a new struct object. It means now the stack is bigger than previous case. But it also means it is faster to access data since there is no jump in memory. The downside, you are not altering the original object, only the copy on the stack. You can use ref/out or return the modified copy value if the result is needed outside the method. Size of myStructObject is 2* sizeof(int) = 8 bytes (most likely more but in a nutshell to get the point).

 -

This brings one major limitation for struct, they cannot inherit or be inherited. This is because when making a class hierarchy, it does not matter how deep and the content of it all, the compiler will make the parameter reference as 4 bytes or 8 bytes (depending on architecture). For a struct to be passed as parameter, the compiler needs to know how much space is needed on the stack to allocate since it will copy all content. Problem with generic type is that compiler is only discovering the object type at runtime, and it would be messy or technically dangerous to try and figure out the full tree of a struct. So the compiler will prevent it.

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Amaresh · Jul 17, 2014 at 12:37 PM 0
Share

@yagizpoyraz Suppose I've a GameObject with a script attached to it. and I'm making a reference to the gameObject via another script.

In this case, should I use class or struct?

avatar image Paprik · Jul 17, 2014 at 01:26 PM 1
Share

For scripts on GameObjects - $$anonymous$$onoBehaviours - you should keep using classes. It's mostly for pure data structures that you'd use a struct. Such as:

 struct PlayerData {
     int hp;
     int level;
     int experience;
     string name;
 }
avatar image yagizpoyraz · Jul 17, 2014 at 01:28 PM 0
Share

@amaresh you should use class in that case. I hope it helped.

avatar image
6

Answer by Oliver-Bogdan · Mar 30, 2017 at 01:24 PM

Here is my take on this. Please read it carefully as it might save you some headache if you are to use structs in the future.

  • If you will be creating lots of objects, you are advised to use a struct, it's faster as it's stored on the stack rather than on the heap.

  • If you need to check for null, use a class. Structs, as all value types
    can't be null. Let's take an example:

A function called GetValidTargetPosition shall return an object of type TargetPosition when the player clicks somewhere on a map. If the player clicks a non-reachable position GetValidTargetPosition function would return null.

As structs can't be null, TargetPosition should be a class if you want to do something like

 TargetPosition targetPosition = GetValidTargetPosition();
 if (targetPosition!=null){
      MoveCharacterTo(targetPosition);
 }

  • If you want to easily modify the data inside a method, use a class. When you call a method with a struct as a parameter a copy of it is created and being sent to the method. Modifying the struct's values inside the method will have no effect outside of the method's scope.

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image edemirci · Jul 27, 2018 at 07:19 AM -2
Share

Please stop spreading false information: A struct IS a nullable type AND can be null https://docs.microsoft.com/en-us/dotnet/csharp/program$$anonymous$$g-guide/classes-and-structs/structs

avatar image Paprik edemirci · Jul 27, 2018 at 09:07 AM 1
Share

Struct is a value type, NOT a nullable type. It can be used as one via: Nullable or $$anonymous$$yStruct?

avatar image yaroslav_ · Mar 09, 2020 at 05:06 AM 0
Share

if you need to check for null often you would better use struct with field isDestroyed and use if (!targetPosition.isDestroyed) it will be much easier on perfomance

avatar image Bunny83 yaroslav_ · Mar 09, 2020 at 04:51 PM 0
Share

This is exactly what the generic Nullable type does. It's actually a struct with two fields. One field contains your actual type, the other is a boolean variable indicating it's "null" state. Everything else is just compiler magic. Assigning null to a Nullable type does not really assign "null" to the variable. It just "marks" it as null. This can be read in the documentation:

Any nullable value type is an instance of the generic System.Nullable<T> structure. You can refer to a nullable value type with an underlying type T in any of the following interchangeable forms: Nullable<T> or T?.


So the Nullable<T> type is just a wrapper struct with some implicit type conversion. I've put the Nullable source on pastebin if you're interested

avatar image
2

Answer by HarshadK · Jul 17, 2014 at 11:56 AM

For your reference:

  • When to use struct in C#?

  • When do you use a struct instead of a class?

  • Choosing Between Class and Struct

  • C# Struct vs. Class

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
1

Answer by Paprik · Jul 17, 2014 at 12:00 PM

Structs can indeed be faster and easier on memory if you use them correctly. Basically, they should be used in cases where you don't care about polymorphism and other class features. You'd normally use structs for smaller groups of common data, especially for use in arrays (as in an array of structs).

I recommend checking out this topic: Where to use struct in C#?. And here's a performance comparison for correct and wrong use: C# performance – class vs struct.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
1

Answer by sysmaya · Feb 01, 2017 at 09:09 AM

This Class attached in Gameobject

    public class ClassAtachGameobject : MonoBehaviour {
         struct myPoint{
             int x;
             int y;
         }
         public myPoint mp;
     
     }

Invoke from other class.

 SomeGameObject.GetComponent<ClassAtachGameobject > ().mp.x=99;
 



Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

33 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Question on UnityScript and C# 1 Answer

Structs in C# Question 3 Answers

Distribute terrain in zones 3 Answers

How to access Vuforia C# library from Javascript 2 Answers

Multiple Cars not working 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges