Search Unity

attaching game object to script reference via editor drag and drop not working

Discussion in 'Getting Started' started by samseed1970, Oct 29, 2018.

  1. samseed1970

    samseed1970

    Joined:
    Oct 19, 2018
    Posts:
    1
    Hi there I'm trying to get to grips with Unity and I've seen several Tutorials say I can drag and drop a UI.Text object from the heirarchy view to a public variable in my script component on the inspector window to ensure that the public variable has an instance at runtime
    (I'm simply trying to display a score value )
    the problem:
    despite seeing this work in several video tutorials and doing it myself with other Gameobjects another projects whenever I drag an drop the destination field doesn't highlight when dragging the text field over the script field and when I drop nothing happens! (it doesn't connect :-( )

    am I doing something wrong or is this a defect or quirk in the editor ..??

    I'm currently blocked with this and v frustrated - any help would be much appreciated :)
     
  2. Bill_Martini

    Bill_Martini

    Joined:
    Apr 19, 2016
    Posts:
    445
    First make sure you've add this to the script header;
    Code (CSharp):
    1. using UnityEngine.UI;
    Then add a public reference to the UI text; (Drag your UI text to this in the inspector)
    Code (CSharp):
    1. public Text myScore;
    And use like;
    Code (CSharp):
    1. myScore = score.ToString();
     
    JoeStrout likes this.
  3. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    One little correction — that last line should be:
    Code (CSharp):
    1. myScore.text = score.ToString();
    ...so you're assigning to the text property of the Text object, rather than to the Text object reference itself.
     
    Bill_Martini likes this.
  4. Bill_Martini

    Bill_Martini

    Joined:
    Apr 19, 2016
    Posts:
    445
    Thank you @JoeStrout for that correction. I'm prone to brain farts!
     
  5. HappyDragonStudio

    HappyDragonStudio

    Joined:
    Aug 30, 2020
    Posts:
    1

    Hi samseed1970, I encountered this same issue today(I may be a few years late, but I hope it helps someone). The problem is that you need to make the variable with type TextMeshProUGUI and not Text. If you are using TextMeshPro(or Text) texts, then this should help:
    Code (CSharp):
    1. public TextMeshProUGUI myScore;
    If that doesn't work try these also(although it should have worked already :p) :
    Code (CSharp):
    1. public TextMesh myScore;
    2. public TextMeshPro myScore;
    Now you will be able to drag and drop your text in the inspector. I hope this fixes the issue.