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

programming problem

Discussion in 'Scripting' started by BBG_dev, Jul 9, 2015.

  1. BBG_dev

    BBG_dev

    Joined:
    May 10, 2015
    Posts:
    6
    Code (JavaScript):
    1. #pragma strict
    2.  
    3. var ScoreUI : UI.Text;
    4. var ScoreInt : int = 0;
    5. var Score2Int : int = 0;
    6.  
    7. var Ball : GameObject;
    8. var BallTransform : Transform;
    9. var BallSpawn : Transform;
    10.  
    11. function Start () {
    12.     BallTransform = GameObject.FindGameObjectsWithTag("Ball");
    13. }
    14.  
    15. function Update () {
    16.     ScoreUI.text = ("Home "+ ScoreInt+" - "+Score2Int+" Away");
    17. }
    18.  
    19. function OnTriggerEnter (other : Collider) {
    20.     if (other.tag == "Ball")
    21.     {
    22.         ScoreInt += 1;
    23.         BallTransform.transform.position = BallSpawn.position;
    24.         ScoreUI.text = ("Home "+ ScoreInt+" - "+Score2Int+" Away");
    25.     }
    26. }
    I get the error "Cannot convert 'unityengine.GameObject[]'to 'unityengine.Transform",
    can someone give me the exact code that works?
     
  2. Glockenbeat

    Glockenbeat

    Joined:
    Apr 24, 2012
    Posts:
    669
    Code (JavaScript):
    1. BallTransform = GameObject.FindGameObjectsWithTag("Ball");
    FindGameObjectsWithTag returns a GameObject, however your variable is of type Transform. Also note that your are using FindGameObjectsWithTag which returns multiple instances in an array if found. So your code should look like this:

    Code (JavaScript):
    1. BallTransform = GameObject.FindGameObjectsWithTag("Ball")[0].transform;
    Note that this is still not error prone as you should probably check if any objects were found at all.
     
  3. SubZeroGaming

    SubZeroGaming

    Joined:
    Mar 4, 2013
    Posts:
    1,008
    Code (CSharp):
    1. function Start () {
    2.     BallTransform = GameObject.FindGameObjectsWithTag("Ball").transform;
    3. }