Home > database >  Unity, C#, pointer workaround?
Unity, C#, pointer workaround?

Time:12-15

I have a field of type Color, let's call it objectColor. I want objectColor "point" to a gameobject that has a color field. For example, the background color of the camera. Or the color of a sprite renderer. When I try "objectColor = mainCamera.backgroundColor" for example, it copies the main cameras background color at that time, and is not linked. I am used to pointers and C . If I was in C I would just make a pointer of Color type, make it point to what mainCamera.backgroundColor is pointing to, and then change the color that way. Any suggestions?

CodePudding user response:

No simple way to do that in C#. You could either hold reference to the class, that owns Color field, but this will prevent you from changing colors of different object types (not sure it is bad actually). Or you could make class wrappers around all objects with color changing functionality and use them through common interface.

interface IColorChange {
   void SetColor(Color color);
}

class CameraWrapper : IColorChange {
   public void SetColor(Color color){
      m_camera.backgroundColor = color;
   }
}

Actually, if you think about it, storing member pointer in c is also not such a great idea. Class instance could die any time and you will be left with a dangling pointer without any way to know about it.

CodePudding user response:

One somewhat unusual way (but not necessarily bad if documented well) would be to use "properties". Those are variables which automatically call their custom setter and getter methods when accessed. You cannot avoid separately keeping a reference to the camera instance with them either however.

Here an unity-independent example: https://dotnetfiddle.net/oxBqXV

using System;

public class Camera
{
    public int color = 20;
}

public class Foo // most likely should inherit from MonoBehavior
{
    Camera _camera;
    public int cam_color_ptr // property
    {
        get
        {
            return _camera.color;
        } // get method

        set
        {
            _camera.color = value;
        } // set method
    }

    public void Start()
    {
        // of course you should acutally get the reference here
        // or have _camera a serializable field to assign in the editor.
        _camera = new Camera();
    }

    public void Print()
    {
        Console.WriteLine("The camera color is: "   cam_color_ptr);
    }
}

public class Program
{
    public static void Main()
    {
        Foo foo = new Foo();
        foo.Start();
        foo.Print();
    }
}
  • Related