How to mix abstract classes and scriptable objects?

Hi, I am trying to improve my knowledge in class coding.

I have DEMs (Digital Elevation Map) which is a fancy word in engineering to say heightmap. I have made a ScriptableObject class to handle the data of these heightmaps.

[CreateAssetMenu(fileName = "New DEM", menuName = "Tools/Terrain Generator/DEM")]
public class DEM : ScriptableObject {

    public static float scale = 0.5f;

    [SerializeField] ComputeShader computeDEM;

    [Header("Image")]
    [SerializeField] Texture2D imageHeightMap;
    [SerializeField] float meterPerPixel;
    [SerializeField] float minValue;

    [Header("Coordinates Range")]
    [SerializeField] Vector2 latitudeRange;
    [SerializeField] Vector2 longitudeRange;
}

The issue is I have 2 types of DEMs, Polar and Cylindrical and both need a different process in order to get the same data. Let me explain.

For instance, I need to convert my coordinates (latitude, longitude) to pixels coordinates. So I have created a method for this:

public Vector2 GetPixelCoordinates(Vector2 coordinates)
{

}

But I need to make 2 different processes depending on the type of the DEM. I could use a simple if statement but it is not very scalable and I want to use this case to improve my coding skills.

I also tried to create an abstract class which I guess is the best case. I have done it like this:

public abstract class DEMStructure
{

    public static float scale = 0.5f;

    public DEMData data { get; private set; }

    public DEMStructure(DEMData data)
    {
        this.data = data;
    }

    public abstract Vector2 GetPixelCoordinates(Vector2 coordinates);
    public abstract bool IsInsideSquare(Vector2 minBorderCoordinates, Vector2 maxBorderCoordinates);
}

public class CylindricalDEM : DEMStructure
{
    public CylindricalDEM(DEMData data) : base(data) { }

    public override Vector2 GetPixelCoordinates(Vector2 coordinates)
    {
       return Vector2.zero;
    }

    public override bool IsInsideSquare(Vector2 minBorderCoordinates, Vector2 maxBorderCoordinates)
    {
       return false;
    }
}

public class PolarDEM : DEMStructure
{
    public PolarDEM(DEMData data) : base(data) { }

    public override Vector2 GetPixelCoordinates(Vector2 coordinates)
    {
        return Vector2.zero;
    }

    public override bool IsInsideSquare(Vector2 minBorderCoordinates, Vector2 maxBorderCoordinates)
    {
        return false;
    }
}

I have removed all the computation to keep it very simple. The only thing you have to know is I need the data to perform the computation in the GetPixelCoordinates method.

Here is my problem, it means I need to always call the data variable and in the data class add a public getter for all the field.

My question is, is there a better way to make this?

To resume, I have a ScriptableObject which handle the data of the DEMs. There are 2 types of DEMs, Polar and Cylindrical. Some methods can be applied on both like getting two dimensional float array and some others need to be different like getting the pixel coordinates.

You have 2 of these. And you think an if/else won’t scale. So … how many more types of heightmap do you expect there to be? Three? Four?

Unless we’re talking at least half a dozen, you’re not improving your coding skill, you’re trying to discipline yourself to a paradigm (OOP) for no good reason and you’re going to write wayyyyy more code than simply adding another else if.

Just if/else until it becomes unsuitable, then refactor. :wink:

3 Likes

I don’t see that as a problem. It’s often good practice to treat your ScriptableObjects as if they are pure data objects. Their single responsibility is to serialize data configurations as assets in the editor. You can add transient state and behavior to them, but that can often invite strange situations later. If you treat them as pure serialized data assets, and pass them into something like a pure C# class, instantiated at runtime as you have done, then you eliminate the possibility of something at runtime corrupting the other transient state data of that asset between play sessions for example.

So, it often will be necessary to expose the ScriptableObject fields, at least via getter properties, so that your runtime scripts can access that data. There’s nothing wrong with that. If you only want your scripts to have readonly access, then you can serialize the private field, and have a get only property. Or, you can use the [SerializeField] attribute on a property with the field attribute target to serialize the backing field of a property like this.

[field:SerializeField] public Texture2D ImageHeightMap { get; private set; }
[field:SerializeField] public float MeterPerPixel { get; set; }

And I would use PascalCase and capitalize the first letter of class members. When I see something camelCase used within a method, I automatically think it must be a local variable. One exception I see is when using a property and an explicit backing field, where the backing field is preceded by an underscore, like _backingField. However, I’ve started using an underscore and PascalCase in that situation because it’s just a convention, so I may as well do what I like. This whole paragraph is about preference. When you have to do some other logic in your property setter or getter you’ll have to split up the declarations.

// I have other code in Update() that continues to synchronize these two properties across two different objects whether there be live changes in the inspector, or via script.
// This is just an example of a complex property/backing field combo declaration.
public int FileSizeLimit { get => _FileSizeLimit; set { if(LogFileWriter != null) LogFileWriter.FileSizeLimit = value; _FileSizeLimit = value; } }
[SerializeField][Delayed][Min(LogFileWriter.MaxBytesPerLog)] private int _FileSizeLimit = LogFileWriter.DefaultFileSizeLimit;
1 Like

What I wanted to say is, I have other projects where I have a lot more of different types. I wanted to use this case as a training to know when should I use interfaces, inheritance or abstract class.

I don’t want to just put if/else statement untill it is not readable anymore. Of course it will scale but with hundreds lines more. I don’t want to do this like a beginner, I want to learn the good practice and not rewritte my code each time I want to add something like the laws of coding say.

Well the point of using either a base class or an interface is substitution. Used properly, you don’t have to care about what derived/specific implementation of a given base class or interface you’re using.

If you have to check for specific types, then at that point you have failed to use either concept and have created an anti-pattern.

What you probably need is some sort of system that can factory these CylindricalDEM. Perhaps with scriptable objects?

public abstract class DEMFactoryBase : ScriptableObject
{
    public abstract DEMStructure GetDEMStructure(DEMData data);
}

[CreateAssetMenu]
public sealed class DEMFactoryCylindrical : DEMFactoryBase
{
    public override DEMStructure GetDEMStructure(DEMData data)
    {
        return new CylindricalDEM(data);
    }
}

Just need a reference to one, then you can give it the required data, it gives you an instance, and you can use it regardless of what specific implementation of DEMStructure it gives you.

Thanks a lot for these examples and explanations.

I knew that it was possible to do this but I never used them since I thought it was not really good in convention or something else.

From what you said, it is good to see the ScriptableObject as pure data handler and use them into other classes to treat and use these data.

In my case, a DEM class to stores the data and a DEM Structure class to treat and use the data through it.

You said, pure data serializer, do you mean that you never put methods inside ScriptableObject, only property fields?

With this method, it means that I create two separated ScriptableObjects for Polar and Cylindrical. So in the create asset menu I will have DEM/Polar or DEM/Cylindrical.

I wanted to have only a DEM as ScriptableObject and in the code determine if it is a Polar or a Cylindrical one by looking at the latitude.

May be it is not the way I should go with, I don’t know that is why I am asking.

I mean you probably only ever need one instance of them, so you can create them, and then remove the Asset menu.

In any case it was just an example. You could do the same thing with plain C# classes and SerializeReference if you have the inspector tooling for it, and thus don’t need to make scriptable object instances for the factories.

When I say only one DEM, I wanted to say only one class but many objects. I want to a have only one DEM class as ScriptableObject to handle data but I will have many of them since I have 234 DEMs. I just prefer not to separate them into 2 differents types when there are created since I want to keep it simple for the future users.

I thing it was not clear, sorry.

Cause I thought to the example you gave me and it is a very goos one which I use for my game but in this case, it does’t work for the reasons I wrote.

I mean it’s still possible with the one scriptable object class. You just need the configuration to be in the plain C# land, serialised into the scriptable object.

SerializeReference makes a lot of stuff like this possible.

1 Like

So here is what I have done, I let you tell me if it is good or better can be done.

I have created my ScriptableObject class DEMData:

using UnityEngine;

[CreateAssetMenu(fileName = "New DEM", menuName = "Tools/Terrain Generator/DEM")]
public class DEMData : ScriptableObject {

    public static float scale = 0.5f;

    [SerializeField] ComputeShader compute;

    [Header("Image")]
    [SerializeField] Texture2D heightmap;
    [SerializeField] float meterPerPixel;
    [SerializeField] float minValue;

    [Header("Coordinates Range")]
    [SerializeField] Vector2 latitudeRange;
    [SerializeField] Vector2 longitudeRange;

    #region Getter & Setter

    public ComputeShader Compute => compute;
    public Texture2D Heightmap => heightmap;
    public float MeterPerPixel => meterPerPixel;
    public float MinValue => minValue;
    public Vector2 LatitudeRange => latitudeRange;
    public Vector2 LongitudeRange => longitudeRange;

    #endregion

    public bool IsCylindrical()
    {
        return latitudeRange.x >= -Coordinates.polesLatitude && latitudeRange.y <= Coordinates.polesLatitude;
    }

    public bool IsPolar()
    {
        return !IsCylindrical();
    }

    public DEMStructure GetStructure()
    {
        return IsCylindrical() ? new CylindricalDEM(this) : new PolarDEM(this);
    }
}

Then I have made the DEMStructure, may be another name would be more suitable.

using UnityEngine;
using System.Collections.Generic;

public abstract class DEMStructure {

    public static float scale = 0.5f;

    public DEMData data { get; private set; }

    public DEMStructure(DEMData data)
    {
        this.data = data;
    }

    public bool Contains(Vector2 coordinates)
    {
        return true;
    }

    public void GetHeightMap(ref float[,] heightmap, float size, Vector2 worldPos, Vector2 coordinates, bool skipInside, IInterpolation interpolation, Crater[] craters = null)
    {
        return heightmap;
    }

    public float GetHeight(int x, int y)
    {
        if (x < 0 || x >= data.Heightmap.width) return 0;
        if (y < 0 || y >= data.Heightmap.height) return 0;

        return ColorToHeight(data.Heightmap.GetPixel(x, y));
    }

    float ColorToHeight(Color color)
    {
        return (color.r * 65025 + color.g * 255 + data.MinValue) * scale; // 255 * 255 = 65025
    }

    public abstract Vector2 GetPixelCoordinates(Vector2 coordinates);
    public abstract bool IsInsideSquare(Vector2 minBorderCoordinates, Vector2 maxBorderCoordinates);
}

public class CylindricalDEM : DEMStructure
{
    public CylindricalDEM(DEMData data) : base(data) { }

    public override Vector2 GetPixelCoordinates(Vector2 coordinates)
    {
        return Vector2.zero;
    }

    public override bool IsInsideSquare(Vector2 minBorderCoordinates, Vector2 maxBorderCoordinates)
    {
        return false;
    }
}

public class PolarDEM : DEMStructure
{
    public PolarDEM(DEMData data) : base(data) { }

    public override Vector2 GetPixelCoordinates(Vector2 coordinates)
    {
        return Vector2.zero;
    }

    public override bool IsInsideSquare(Vector2 minBorderCoordinates, Vector2 maxBorderCoordinates)
    {
        return false;
    }
}

So from the DEMData class I can call the GetStructure method and use it as my main class to use the data.

Does it seem right to you?