0
\$\begingroup\$

I have scene with camera, light source and empty object with an attached script.

I generate red line but its material is never set. Ho can I set, in script, its material as Default-Line? Without this it is shown as magenta, not red.

I know that it is root cause as setting material manually in editor fixes it.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
using System.Linq;
 
public class GraphDisplay : MonoBehaviour {
    void Start() {
        var a = new Vector3(0.0f, 0.0f, 0.0f);
        var b = new Vector3(0.0f, 0.0f, 10.0f);
        var pointArray = new Vector3[2];
        pointArray[0] = a;
        pointArray[1] = b;
        Color color = Color.red;
 
        var go = new GameObject("line");
        var lr = go.AddComponent<LineRenderer>();
            lr.startColor = color;
            lr.endColor = color;
        }
        lr.startWidth = 5;
        lr.endWidth = 5;
        lr.positionCount = pointArray.Length;
 
        lr.SetPositions(pointArray);
    }
}

I tried using recommended solution from https://gamedev.stackexchange.com/a/96966/96768 but that simply crashes with Trying to create a material from string - this is no longer supported.

Note that I want to set it entirely within code, without requiring any manual steps like setting some global variables using inspector.

\$\endgroup\$
3
  • \$\begingroup\$ Isn't having inspector reference to the material (then apply it using lr.material) not possible? \$\endgroup\$
    – Nikaas
    Nov 14 '21 at 8:39
  • \$\begingroup\$ @Nikaas It is possible but I want to avoid it - I want to make code that does not rely on external manual setup beyond attaching script to an empty object in the empty scene (yes, I know that "pure code" solution is not typical in Unity). \$\endgroup\$ Nov 14 '21 at 8:42
  • \$\begingroup\$ You can try 'Resources.Load<Material>("MaterialPath");' - docs.unity3d.com/ScriptReference/Resources.Load.html . But it is much slower than inspector ref (it reads from disk, so you can try caching it). And it is prone to errors because it relies on path string. \$\endgroup\$
    – Nikaas
    Nov 14 '21 at 13:16

You must log in to answer this question.

Browse other questions tagged .