-1

I am trying to write a C# script in Unity that would move other objects in the game. I tried this code below, but it didn't work. The errors are saying that REDpos, RRDpos, RADpos, and RCDpos, do not exist in the current context. Please help me figure out how to fix this! I am abeginner, so sorry if it's really obvious.

Here is my code:

using UnityEngine;
using System.Collections;

public class TeamSelect : MonoBehaviour {

    public GameObject RCD;
    public GameObject RAD;
    public GameObject RED;
    public GameObject RRD;

    // Use this for initialization
    void Start () {
        RCD = GameObject.Find("RCD");
        RAD = GameObject.Find("RAD");
        RED = GameObject.Find("RED");
        RRD = GameObject.Find("RRD");
    }

    // Update is called once per frame
    void Update () {
        RCDpos = RCD.transform.position.x;
        RADpos = RAD.transform.position.x;
        REDpos = RED.transform.position.x;
        RRDpos = RRD.transform.position.x;

        if (Input.GetKey("right")) {
            RCDpos = RCDpos - 0.1;
            RADpos = RADpos - 0.1;
            REDpos = REDpos - 0.1;
            RRDpos = RRDpos - 0.1;
        }

        if (Input.GetKey("left")) {
            RCDpos = RCDpos + 0.1;
            RADpos = RADpos + 0.1;
            REDpos = REDpos + 0.1;
            RRDpos = RRDpos + 0.1;
        }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dallas White
  • 83
  • 1
  • 10

2 Answers2

0

well of course they don't exist...you never defined them :\

RCDpos = RCD.transform.position.x;
RADpos = RAD.transform.position.x;
REDpos = RED.transform.position.x;
RRDpos = RRD.transform.position.x;

before assign something to RCDpos RADpos REDpos RRDpos you have to define them, you defined RCD RAD RED RRD GameObject only

try to add this after you defined your GameObjects:

Vector3 RCDpos;  
Vector3 RADpos; 
Vector3 REDpos; 
Vector3 RRDpos; 

modify your Update in this way:

RCDpos = new Vector3(RCD.transform.position.x,0,0);
RADpos = new Vector3(RAD.transform.position.x,0,0);
REDpos = new Vector3(RED.transform.position.x,0,0);
RRDpos = new Vector3(RRD.transform.position.x,0,0);

i think should be work.

Samuel C.
  • 75
  • 3
0

Try this:

class Obj : MonoBehaviour 
{   
    //public so other classes can get it
    public Vector3 pos = transform.position; 

    void Update ()  
    {  
        //keeps pos updated
        pos = transform.position;
    }
    public void move (Vector3 vect) 
    {  
        //moves player
        transform.position += vect;
    }
}  

class team  
{ 
    public Obj obj;  
    void Start () 
    {
        obj.move(new Vector3(0f,0f,0f));  
    } 
}

this moves the object from team class. But does not do it from player input.