trouble changing variables of another script
hi! I have a problem: can't change the variable "count" of the second script from the first one. I guess is an easy problem... but I've started programming just last week. ^_^' (the scripts should create an exit from the level when you've killed 40 enemies)
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Zombie4Beha : MonoBehaviour { public GameObject contatore, player; private float speed; private Rigidbody2D rb; private int pv;
void Start()
{
gameObject.tag = "zombie4";
rb = GetComponent<Rigidbody2D>();
rb.drag = 10;
pv = 4;
speed = 5;
}
void Update()
{
GameObject player = GameObject.FindGameObjectWithTag("character");
rb.rotation = 0;
Vector2 proprio = new Vector2(rb.position.x, rb.position.y);
Vector2 dir = new Vector2(player.GetComponent<Rigidbody2D>().position.x, player.GetComponent<Rigidbody2D>().position.y);
rb.AddForce(-(proprio - dir).normalized * speed);
if (pv <= 0)
Destroy(gameObject);
}
private void OnTriggerEnter2D(Collider2D coll)
{
if (coll.gameObject.tag == "proiettile")
pv = pv - 1;
}
private void OnDestroy()
{
contatore.GetComponent<DoorpawnBeha>().count = contatore.GetComponent<DoorpawnBeha>().count + 1;
}
}
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class DoorpawnBeha : MonoBehaviour { public int count; public GameObject porta; public Transform oggSpawn;
private void Start()
{
count = 0;
}
private void Update()
{
Debug.Log(count);
if (count >= 40)
Instantiate(porta, oggSpawn.position, oggSpawn.rotation);
}
}
thanks from now for the help!
Answer by PersianKiller · Sep 19, 2017 at 07:00 PM
hey
script 1
public DoorpawnBeha name;
void Start(){
name=FindObjectOfType<DoorpawnBeha>();
}
so now you can access to DoorpawnBeha script with calling name.
for example in your first script you can now use something like this
void Update(){
if(name.score>40){
//do something
}
lol, after only 3 days I had already forgotten that XD
i have the same problem, did exactly what you said to do, but it still doesn't work for me. any idea why??
@maxance710 look at this example.
I want when I get 100 scroes in script 1,then another script show me a message like this (Yay)
* script1
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class script1 : $$anonymous$$onoBehaviour {
public int score;
// Use this for initialization
void OnTriggerEnter2D(Collider2D other){
if(other.CompareTag("coin")){
score += 10;
Destroy (other.gameObject);
}
}
}
* script 2
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class script2 : $$anonymous$$onoBehaviour {
public script1 s1;
// Use this for initialization
void Start () {
s1 = FindObjectOfType<script1> ();
}
// Update is called once per frame
void Update () {
if (s1.score > 100) {
Debug.Log ("YAY");
}
}
}