I’m currently doing a proof of concept similar to how MS paint works. I’m using Line Renderer to create basic drawing capabilities, but there’s a problem. The Instantiate process always shows up outside of any canvas, meaning it’s always covered by my background. I’ve tried making it a child of the initial and of a separate canvas in the code, but that didn’t work. I’ve tried the ‘creating a new camera and linking it to one canvas’ trick, but that didn’t work (though I might not have understood that completely). I’ve also tried masking layers, though I don’t understand that 100%. It still shows up outside of any canvas, so it’s always under my background. Any ideas for a good solution?
Here’s my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Draw : MonoBehaviour
{
public GameObject canvasObject;
public Camera m_camera;
public GameObject brush;
LineRenderer currentLineRenderer;
Vector2 lastPos;
private void Update()
{
Drawing();
}
void Drawing()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
CreateBrush();
}
else if (Input.GetKey(KeyCode.Mouse0))
{
PointToMousePos();
}
else
{
currentLineRenderer = null;
}
}
void CreateBrush()
{
GameObject brushInstance = Instantiate(brush);
// Next line is attempt as making the canvas the parent
brushInstance.transform.SetParent(canvasObject.transform, false);
currentLineRenderer = brushInstance.GetComponent ();
Vector2 mousePos = m_camera.ScreenToWorldPoint(Input.mousePosition);
currentLineRenderer.SetPosition(0, mousePos);
currentLineRenderer.SetPosition(1, mousePos);
}
void AddAPoint(Vector2 pointPos)
{
currentLineRenderer.positionCount++;
int positionIndex = currentLineRenderer.positionCount - 1;
currentLineRenderer.SetPosition(positionIndex, pointPos);
}
void PointToMousePos()
{
Vector2 mousePos = m_camera.ScreenToWorldPoint(Input.mousePosition);
if (lastPos != mousePos)
{
AddAPoint(mousePos);
lastPos = mousePos;
}
}
}
And here’s my hierarchy:
Before Instantiating
After Instantiating
For further elaboration:
I followed this tutorial