Search Unity

How do I get a pointer or equivalent to a struct in C Sharp?

Discussion in 'Scripting' started by arkon, Nov 28, 2012.

  1. arkon

    arkon

    Joined:
    Jun 27, 2011
    Posts:
    1,122
    In C I'd have an array of structures then in the code somewhere create a pointer to one of the structures in the array.
    This gives me speedy access both read and write to the structure. How do I do this in C Sharp? For example my structure:

    Code (csharp):
    1.  public struct slot_struct
    2.  {
    3.     public float Health;
    4.     public float SetPower;
    5.  
    6.     public slot_struct(float health,float setpower)
    7.     {
    8.       Health = health;
    9.       SetPower = setpower;
    10.     }
    11. }
    initialised like so:

    Code (csharp):
    1. public slot_struct[] Slots =
    2. {
    3.     new slot_struct(100,25),
    4.     new slot_struct(50,10),
    5. };
    6.  
    Then in code what is the way to access the data to read and write it. This example below only lets me read the data as it
    seems to create a copy and not be a pointer or reference to the entry in the array:-


    Code (csharp):
    1.  slot_struct Slot = Slots[1];
    2.    Slot.Health = 22.5f;            // This doesn't actually write the data to the struct in the array  which is my problem
    3.  
    Any ideas? in C I'd just use slot_struct *Slot = &Slots[1];
     
  2. Errorsatz

    Errorsatz

    Joined:
    Aug 8, 2012
    Posts:
    555
    If you're passing this to a function, you can use 'ref'.
    Example:
    void ModifyHealth ( ref slot_struct slot )
    ...
    ModifyHealth(ref Slots[1]); // Modifies Slots[1]


    If you want to reference a something by pointer in general, use a class instead of a struct - all uses of a classed object are by reference, rather than value.
    Example:
    class Slot
    ...
    Slot[] Slots = new Slot[10];
    Slots[1] = new Slot();
    ...
    Slot curSlot = Slots[1];
    curSlot.Health = 22.5f; // Modifies Slots[1]
     
  3. arkon

    arkon

    Joined:
    Jun 27, 2011
    Posts:
    1,122
    Cool, I'll convert the structs to classes and try again. Thanks.
     
  4. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,532