Arvtesh / UnityFx.Outline

Screen-space outlines for Unity3d.
MIT License
1.26k stars 90 forks source link

[Script] Per-object outline for URP #41

Closed Maclay74 closed 2 years ago

Maclay74 commented 3 years ago

I wrote a small script to switch outline for single object, feel free to use. If there is a more elegant way to achieve that using SRP, let me know please.


using UnityEngine;

public class OutlineSwitch : MonoBehaviour {

    private bool _currentOutline = false;
    public bool outline;

    public string outlineLayerName = "Outline";

    private int _defaultLayer;
    private int _outlineLayer;

    private void Start() {
        _defaultLayer = gameObject.layer;
        _outlineLayer = LayerMask.NameToLayer(outlineLayerName);
    }

    public void OnDisable() {
        gameObject.layer = _defaultLayer;
    }

    public void OnEnable() {
        OnOutlineChanged();
    }

    void Update() {
        if (_currentOutline != outline) {
            _currentOutline = outline;
            OnOutlineChanged();
        }
    }

    public void SetOutline(bool value) {
        _currentOutline = outline = value;
        OnOutlineChanged();
    }

    private void OnOutlineChanged() {

        if (_currentOutline && gameObject.layer != _outlineLayer) {
            gameObject.layer = _outlineLayer;
        }

        if (!_currentOutline && gameObject.layer != _defaultLayer) {
            gameObject.layer = _defaultLayer;
        }
    }
}
Arvtesh commented 3 years ago

Using game object layers (or rendering layer mask) is fine. There is an error in the script though: Start is called after OnEnable and OnEnable assumes _defaultLayer is initialized.