Noticias

¡RECUERDA QUE SI ERES UN NUEVO USUARIO, DEBES PRESENTARTE PARA PODER PUBLICAR MENSAJES! | TENEMOS CANAL OFICIAL DE TELEGRAM: t.me/unity3dspain

Pasar el valor int de un script a otro en un mismo gameobject

Iniciado por sab, Marzo 17, 2016, 06:38:09 AM

Tema anterior - Siguiente tema
Marzo 17, 2016, 06:38:09 AM Ultima modificación: Marzo 17, 2016, 06:47:29 AM por sab
Saludos a todos llevo rato tratando de pasar el valor de una variable de un script a otro (los 2 están en el mismo gameObject -Main Camara-), lo que trato de hacer es asignarle el valor int de "puntuacion" a otra variable int "score", pero no lo logro; using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;public class Timer : MonoBehaviour{
    private int score;
    void Update()
    {
        Puntuacion variable = GetComponent<Puntuacion>();
        score = variable.puntuacion;
 Alguien me puede ayudar en decirme que estoy haciendo mal??? Gracias a todos y saludos!!!!!!!!

Hola!! Te da errores al compilar?Aparte la primera linea de codigo que pones dentro de la funcion Update(), deberias ponerla en una funcion Start() ya que lo que haces creo que consume bastante sobre todo para hacerlo en cada frame.

void Start()
{
    Puntuacion variable = GetComponent<Puntuacion>();
}
void Update()
{
    score = variable.puntuacion;
}
Despues debes asegurarte de que la variable "int puntuacion;" de tu script Puntuacion sea publica quedaria "public int puntuacion;". Aunque si no fuese así te hubiese dado errores de compilacion... de ahi la pregunta que te hice al principio.Comprueba tambien que el script "Puntuacion" esté activado en el inspector.... por si acasoMira eso porque no se me ocurre porqué puede suceder tu problema...Saludos

Marzo 18, 2016, 06:12:17 AM #2 Ultima modificación: Marzo 18, 2016, 06:46:56 AM por sab
Gracias por tu ayuda http://unityspain.com/profile/25880-ftejada/?do=hovercard&referrer=http%253A%252F%252Funityspain.com%252Ftopic%252F35414-pasar-el-valor-int-de-un-script-a-otro-en-un-mismo-gameobject%252F%253F_fromLogin%253D1" title="Go to ftejada's profile" id="ips_uid_5" style="box-sizing: border-box; color: inherit; text-decoration: none; background-color: transparent;" href="<___base_url___>/profile/25880-ftejada/">ftejada, te cuento que no me da ningún error al compilar. Luego si pongo 
void Update()
{
    score = variable.puntuacion;
}
solamente en update (entonces si muestra error al compilar) me dice que variable no existe en el contexto (tengo que poner los 2 o update o en start)por ultimo la variable puntuacion si es publica pero esta cifrada (por lo que NO activado en el inspector): public int puntuacion {
        get { return _puntuacion ^ key; }
        set {
            key = Random.Range(0, int.MaxValue);
            _puntuacion = value ^ key;
        }
    } Espero que me podas ayudar, pues no entiendo bien que falla....

Cita de: sab date=1458277937" data-ipsquote="" data-cite="sab" class="ipsQuote">Gracias por tu ayuda ftejada, te cuento que no me da ningún error al compilar. Luego si pongo 
void Update(){
    score = variable.puntuacion;
}
solamente en update (entonces si muestra error al compilar) me dice que variable no existe en el contexto (tengo que poner los 2 o update o en start)por ultimo la variable puntuacion si es publica pero esta cifrada (por lo que NO activado en el inspector): public int puntuacion {
        get { return _puntuacion ^ key; }
        set {
            key = Random.Range(0, int.MaxValue);
            _puntuacion = value ^ key;
        }
    } Espero que me podas ayudar, pues no entiendo bien que falla....
pasame los dos scripts para examinarlos mejor.

gracias, de nuevo, aqui te dejo las scripts;using UnityEngine;
using System.Collections;public class Puntuacion : MonoBehaviour {    private int key = 0;
    private int _puntuacion = 0;
    public int puntuacion {
        get { return _puntuacion ^ key; }
        set {
            key = Random.Range(0, int.MaxValue);
            _puntuacion = value ^ key;
        }
    }    public TextMesh marcador;    // Use this for initialization
    void Start () {
        NotificationCenter.DefaultCenter().AddObserver (this, "IncrementarPuntos");
        NotificationCenter.DefaultCenter().AddObserver (this, "PersonajeHaMuerto");
        ActualizarMarcador ();
    }    void PersonajeHaMuerto (Notification notification){
        if (puntuacion > EstadoJuego.estadoJuego.puntuacionMaxima) {
            //Debug.Log ("NUEVO RECORD!! MAXIMA: " + EstadoJuego.estadoJuego.puntuacionMaxima + " ACTUAL: " + puntuacion);
            EstadoJuego.estadoJuego.puntuacionMaxima = puntuacion;
            EstadoJuego.estadoJuego.Guardar ();
        } /*else {            Debug.Log ("RECORD NO SUPERADO!! MAXIMA: " + EstadoJuego.estadoJuego.puntuacionMaxima + " ACTUAL: " + puntuacion);
            }*/        //Con el siguiente codigo enviamos la puntuacion obtenida a Google Play Games        Social.ReportScore(puntuacion, "VALORGENERADO", (bool success) => { });        
        //Activamos las medallas con el siguiente codigo        if (puntuacion >= 200) {
            Social.ReportProgress("VALORGENERADO", 100.0, (bool success) => { });
        }        if (puntuacion >= 400)
        {
            Social.ReportProgress("VALORGENERADO", 100.0, (bool success) => { });
        }        if (puntuacion >= 600)
        {
            Social.ReportProgress("VALORGENERADO", 100.0, (bool success) => { });
        }        if (puntuacion >= 800)
        {
            Social.ReportProgress("VALORGENERADO", 100.0, (bool success) => { });
        }        if (puntuacion >= 1000)
        {
            Social.ReportProgress("VALORGENERADO", 100.0, (bool success) => { });
        }
    }    void IncrementarPuntos(Notification notificacion){
        int puntosAIncrementar = (int)notificacion.data;
        puntuacion +=puntosAIncrementar;
        ActualizarMarcador ();
    }    void ActualizarMarcador(){
        marcador.text = puntuacion.ToString();
        }    // Update is called once per frame
    void Update () {
    
    }
}    :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::Y el otro:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: 
public class Timer : MonoBehaviour{
    private int score = 1;
    private int LevelAmount = 3;
    private int CurrentLevel;
    // Use this for initialization
    void Start()
    {
        CheckCurrentLevel();
       // StartCoroutine(Time());
    }
    void Update()
    {
        Puntuacion variable = GetComponent<Puntuacion>();
        score = variable.puntuacion;    }    /*    IEnumerator Time()
    {
        yield return new WaitForSeconds(5f);
        //Application.LoadLevel(1);
        SceneManager.LoadScene("Menu");
    }    */    void CheckCurrentLevel()
    {
        for (int i = 1; i < LevelAmount; i++)
        {
            //if (Application.loadedLevelName == "Level" + i)
            if (SceneManager.GetActiveScene().name == "Level" + i)
            {
                CurrentLevel = i;
                SaveMyGame();
            }
        }    }    void SaveMyGame()
    {
        int NextLevel = CurrentLevel + 1;
        if (NextLevel < LevelAmount)
        {
            //Desbloquea el proximo nivel
        
            PlayerPrefs.SetInt("Level" + NextLevel.ToString(), 1);
            PlayerPrefs.SetInt("Level" + CurrentLevel.ToString() + "_score", score);
        }
        else
        {
            PlayerPrefs.SetInt("Level" + CurrentLevel.ToString() + "_score", score);        }
    }
}  Suludos y gracias...............

[quote author=sab" data-ipsquote-contapp="forums" data-ipsquote-contenttype="forums" data-ipsquote-contentclass="forums_Topic" data-ipsquote-contentid="35414" data-ipsquote-contentcommentid="128312">Gracias por tu ayuda http://unityspain.com/profile/25880-ftejada/?do=hovercard&referrer=http%253A%252F%252Funityspain.com%252Ftopic%252F35414-pasar-el-valor-int-de-un-script-a-otro-en-un-mismo-gameobject%252F%253F_fromLogin%253D1" title="Go to ftejada's profile" id="ips_uid_5" style="box-sizing: border-box; color: inherit; text-decoration: none; background-color: transparent;" href="<___base_url___>/profile/25880-ftejada/">ftejada, te cuento que no me da ningún error al compilar. Luego si pongo 
void Update(){
    score = variable.puntuacion;
}
solamente en update (entonces si muestra error al compilar) me dice que variable no existe en el contexto (tengo que poner los 2 o update o en start)por ultimo la variable puntuacion si es publica pero esta cifrada (por lo que NO activado en el inspector): public int puntuacion {
        get { return _puntuacion ^ key; }
        set {
            key = Random.Range(0, int.MaxValue);
            _puntuacion = value ^ key;
        }
    } Espero que me podas ayudar, pues no entiendo bien que falla....[/quote]para que no te de errores al compilar con el ejemplo que te dio @ftejada debes declarar la variable fuera del start

Muchas gracias, isai creo que ese si esta claro, solo el problema principal es el que falta


[quote author=sab date=1458324481" data-ipsquote="" data-cite="sab" class="ipsQuote">gracias, de nuevo, aqui te dejo las scripts;using UnityEngine;
using System.Collections;public class Puntuacion : MonoBehaviour {    private int key = 0;
    private int _puntuacion = 0;
    public int puntuacion {
        get { return _puntuacion ^ key; }
        set {
            key = Random.Range(0, int.MaxValue);
            _puntuacion = value ^ key;
        }
    }    public TextMesh marcador;    // Use this for initialization
    void Start () {
        NotificationCenter.DefaultCenter().AddObserver (this, "IncrementarPuntos");
        NotificationCenter.DefaultCenter().AddObserver (this, "PersonajeHaMuerto");
        ActualizarMarcador ();
    }    void PersonajeHaMuerto (Notification notification){
        if (puntuacion > EstadoJuego.estadoJuego.puntuacionMaxima) {
            //Debug.Log ("NUEVO RECORD!! MAXIMA: " + EstadoJuego.estadoJuego.puntuacionMaxima + " ACTUAL: " + puntuacion);
            EstadoJuego.estadoJuego.puntuacionMaxima = puntuacion;
            EstadoJuego.estadoJuego.Guardar ();
        } /*else {            Debug.Log ("RECORD NO SUPERADO!! MAXIMA: " + EstadoJuego.estadoJuego.puntuacionMaxima + " ACTUAL: " + puntuacion);
            }*/        //Con el siguiente codigo enviamos la puntuacion obtenida a Google Play Games        Social.ReportScore(puntuacion, "VALORGENERADO", (bool success) => { });        
        //Activamos las medallas con el siguiente codigo        if (puntuacion >= 200) {
            Social.ReportProgress("VALORGENERADO", 100.0, (bool success) => { });
        }        if (puntuacion >= 400)
        {
            Social.ReportProgress("VALORGENERADO", 100.0, (bool success) => { });
        }        if (puntuacion >= 600)
        {
            Social.ReportProgress("VALORGENERADO", 100.0, (bool success) => { });
        }        if (puntuacion >= 800)
        {
            Social.ReportProgress("VALORGENERADO", 100.0, (bool success) => { });
        }        if (puntuacion >= 1000)
        {
            Social.ReportProgress("VALORGENERADO", 100.0, (bool success) => { });
        }
    }    void IncrementarPuntos(Notification notificacion){
        int puntosAIncrementar = (int)notificacion.data;
        puntuacion +=puntosAIncrementar;
        ActualizarMarcador ();
    }    void ActualizarMarcador(){
        marcador.text = puntuacion.ToString();
        }    // Update is called once per frame
    void Update () {
    
    }
}    :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::Y el otro:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: 
public class Timer : MonoBehaviour{
    private int score = 1;
    private int LevelAmount = 3;
    private int CurrentLevel;
    // Use this for initialization
    void Start()
    {
        CheckCurrentLevel();
       // StartCoroutine(Time());
    }
    void Update()
    {
        Puntuacion variable = GetComponent<Puntuacion>();
        score = variable.puntuacion;    }    /*    IEnumerator Time()
    {
        yield return new WaitForSeconds(5f);
        //Application.LoadLevel(1);
        SceneManager.LoadScene("Menu");
    }    */    void CheckCurrentLevel()
    {
        for (int i = 1; i < LevelAmount; i++)
        {
            //if (Application.loadedLevelName == "Level" + i)
            if (SceneManager.GetActiveScene().name == "Level" + i)
            {
                CurrentLevel = i;
                SaveMyGame();
            }
        }    }    void SaveMyGame()
    {
        int NextLevel = CurrentLevel + 1;
        if (NextLevel < LevelAmount)
        {
            //Desbloquea el proximo nivel
        
            PlayerPrefs.SetInt("Level" + NextLevel.ToString(), 1);
            PlayerPrefs.SetInt("Level" + CurrentLevel.ToString() + "_score", score);
        }
        else
        {
            PlayerPrefs.SetInt("Level" + CurrentLevel.ToString() + "_score", score);        }
    }
}  Suludos y gracias...............[/quote]Hola sab... Lo que te ha dicho juanma_teso es correcto y deberias cambiarlo. En el enlace que te da viene muy bien esplicado. Otro tema que me gustaría pregunterte es para qué quieres la potencia de la puntuación? Porqué no la puntuacion sin más?? Es por algo en concreto?? Por otro lado y disculpa no habertelo aclarado correctamente, es que los scripts que quería que me mandases eran estos mismos pero con las modificaciones que hiciste en la que te daban errores de compilacion, despues de que yo te sugiriese los cambios. Ya que seguramente isai lleve razón y vayan por ahí los tiros.Puedes introducir el codigo de los scripts cuando lo posteesde una manera mejor... Arriba de cada recuadro donde escribes el mensaje, hay diversas opciones entre ellas

muchas gracias a todos, http://unityspain.com/profile/26011-juanma_teso/?do=hovercard&referrer=http%253A%252F%252Funityspain.com%252Ftopic%252F35414-pasar-el-valor-int-de-un-script-a-otro-en-un-mismo-gameobject%252F%253F_fromLogin%253D1" title="Go to juanma_teso's profile" id="ips_uid_4" style="box-sizing: border-box; color: inherit; text-decoration: none; background-color: transparent;" href="<___base_url___>/profile/26011-juanma_teso/">juanma_teso voy a probar a ver si lo soluciono, http://unityspain.com/profile/25880-ftejada/?do=hovercard&referrer=http%253A%252F%252Funityspain.com%252Ftopic%252F35414-pasar-el-valor-int-de-un-script-a-otro-en-un-mismo-gameobject%252F%253F_fromLogin%253D1" title="Go to ftejada's profile" id="ips_uid_6" style="box-sizing: border-box; color: inherit; text-decoration: none; background-color: transparent;" href="<___base_url___>/profile/25880-ftejada/">ftejada, lo de la puntuación es por que lo estoy haciendo con un tutorial de: "Hagamos Videojuegos", en el que recomienda hacerlo de esa manera para evitar hackeos....., muchísimas gracias por explicarme como agregar bien los códigos, busqué por todas partes y no lo conseguí, ahora ya se como, ademas como decís, sí revisé lo que dice isai, y si lo arreglé, al menos eso creo voy a trabajar en lo me recomiendan los tres y les cuento, gracias infinitas!!!!!!!!!!

Saludos, les cuento que ya casi logro solucionar el problema, cambiando la forma en que lo encaré y sin modificarlo mucho (después cambiare lo que me indica http://unityspain.com/profile/26011-juanma_teso/?do=hovercard&referrer=http%253A%252F%252Funityspain.com%252Ftopic%252F35414-pasar-el-valor-int-de-un-script-a-otro-en-un-mismo-gameobject%252F%253F_fromLogin%253D1" title="Go to juanma_teso's profile" id="ips_uid_4" style="box-sizing: border-box; color: inherit; text-decoration: none; background-color: transparent;" href="<___base_url___>/profile/26011-juanma_teso/">juanma_teso, cuando lo estudie y entienda bien), por el momento de esta manera esta quedando bien lo único es que:
void SaveMyGame()
me reconoce el valor de puntuacion con que inicia = 0, y no el final, ejemplo = 5.entonces lo que necesito es reparar como hacer que reconozca el valor final, ojalá me puedan ayudar, gracias........
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class Timer : MonoBehaviour{

    public int score;
    public Puntuacion puntuacion;
    private int LevelAmount = 24;
    private int CurrentLevel;


    // Use this for initialization
    void Start()
    {
        CheckCurrentLevel();
        //StartCoroutine(Time());
       
    }

   

    void TerminarJuego(Notification notification){

        ActualizarMarcador();
    }

   

        void Update()
    {
        //score = variable.puntuacion;

        //score = puntuacion.puntuacion;
        //Debug.Log("SCORE" + score);

    }

   

    void ActualizarMarcador()
    {
        score = puntuacion.puntuacion;
        Debug.Log("SCORE = " + score);
    }

       

    /*

    IEnumerator Time()
    {
        yield return new WaitForSeconds(5f);
        SceneManager.LoadScene("Menu");
    }

    */

    void CheckCurrentLevel()
    {
        for (int i = 1; i < LevelAmount; i++)
        {
            if (SceneManager.GetActiveScene().name == "Level" + i)
            {
                CurrentLevel = i;
                SaveMyGame();
            }
        }

    }

    void SaveMyGame()
    {
        int NextLevel = CurrentLevel + 1;
        if (NextLevel < LevelAmount)
        {
            //Desbloquea el proximo nivel
       
            PlayerPrefs.SetInt("Level" + NextLevel.ToString(), 1);
            PlayerPrefs.SetInt("Level" + CurrentLevel.ToString() + "_score", score);
            Debug.Log("_ScoreONE = " + score);
        }
        else
        {
            PlayerPrefs.SetInt("Level" + CurrentLevel.ToString() + "_score", score);
            Debug.Log("_ScoreTWO = " + score);
        }
    }
}
 

 tu metodo solo lo llamas en start?, es posible que por eso no se guarde[quote author=sab" data-ipsquote-contapp="forums" data-ipsquote-contenttype="forums" data-ipsquote-contentclass="forums_Topic" data-ipsquote-contentid="35414" data-ipsquote-contentcommentid="128489">
  void CheckCurrentLevel(){
        for (int i = 1; i < LevelAmount; i++)
        {
            if (SceneManager.GetActiveScene().name == "Level" + i)
            {
                CurrentLevel = i;
                SaveMyGame();
            }
        }

    }
[/quote]

Marzo 22, 2016, 12:13:19 AM #12 Ultima modificación: Marzo 22, 2016, 12:13:35 AM por sab
Muchas gracias, http://unityspain.com/profile/28137-isai/?do=hovercard&referrer=http%253A%252F%252Funityspain.com%252Ftopic%252F35414-pasar-el-valor-int-de-un-script-a-otro-en-un-mismo-gameobject%252F" title="Go to isai's profile" id="ips_uid_4" style="box-sizing: border-box; color: inherit; text-decoration: none; outline: 0px; background-color: transparent;" href="<___base_url___>/profile/28137-isai/">isai realmente es por eso que me gusta preguntar, por que gracias a esto comprendo cosas que no sabía (es lo malo de ser principiante, no ver las cosas que parecen obvias para cualquiera), voy a revisar como lo cambio y les informo. Muchas gracias

[quote author=sab" data-ipsquote-contapp="forums" data-ipsquote-contenttype="forums" data-ipsquote-contentclass="forums_Topic" data-ipsquote-contentid="35414" data-ipsquote-contentcommentid="128497">Muchas gracias, http://unityspain.com/profile/28137-isai/?do=hovercard&referrer=http%253A%252F%252Funityspain.com%252Ftopic%252F35414-pasar-el-valor-int-de-un-script-a-otro-en-un-mismo-gameobject%252F" title="Go to isai's profile" id="ips_uid_4" style="box-sizing: border-box; color: inherit; text-decoration: none; outline: 0px; background-color: transparent;" href="<___base_url___>/profile/28137-isai/">isai realmente es por eso que me gusta preguntar, por que gracias a esto comprendo cosas que no sabía (es lo malo de ser principiante, no ver las cosas que parecen obvias para cualquiera), voy a revisar como lo cambio y les informo. Muchas gracias[/quote]dale un vistazo a esto http://docs.unity3d.com/es/current/Manual/ExecutionOrder.html para que tengas una idea del orden de ejecucion de las funciones de unity y sepas donde poner cada cosa ;)

Buenísimo!!!!!!!!! isai, muchísimas gracias........................

Etiquetas: