Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Instantiate canvas on mouse position?[Solved-ish]

Discussion in 'Scripting' started by Masonish, Oct 27, 2015.

  1. Masonish

    Masonish

    Joined:
    Oct 27, 2015
    Posts:
    1
    Hi there, I've been trying to instantiate a text on my mouse position for my clicker game, although it works just fine by instantiating a gameObject, whenever i instantiate a canvas with a text the text is always anchored to the middle of the screen, no matter the position i instantiate it on
    Code (CSharp):
    1.  
    2.     void OnMouseDown()
    3.     {
    4.         corgiAmount += addAmount;
    5.         Instance();
    6.  
    7.     }
    8.  
    9.     void Instance()
    10.     {
    11.         pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    12.         pos.z = 10;
    13.         Instantiate(textCanvas, pos, Quaternion.identity);
    14.         a.text = "+" + addAmount.ToString("F0") + " corgis";
    15.     }
    Help would be greatly appreciated!

    EDIT: Didn't get it working but skip the canvas and it works pretty fine
     
    Last edited: Dec 5, 2015
  2. Elmdran

    Elmdran

    Joined:
    Oct 28, 2014
    Posts:
    34
    I'm assuming you already have a canvas and you are not instantiating a canvas but a UI.Text element.
    If so, the problem might be that your text element is not instantiated as a child of the canvas.

    Try this:
    Code (CSharp):
    1. void Instance()
    2.     {
    3.         pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    4.         pos.z = 10;
    5.         GameObject go;
    6.         go = Instantiate(textCanvas, pos, Quaternion.identity) as GameObject;
    7.         go.transform.parent = canvas.transform.parent;
    8.         go.transform.position = pos;
    9.         a.text = "+" + addAmount.ToString("F0") + " corgis";
    10.     }