Jump to content
  • Advertisement
dell96

Help please !!!

Recommended Posts

Hi there I'm new to unity and C# and i want to make my first Android game and I'm having a problem when my player collides with the cratepipe in the game the spawning crate wont stop  i need help with this i want to stop the spawning when the  gameobject "player" hits the crates and stop. my player move by tilting 

I'm going to leave all the scripts I'm using so far please help me what should i do....?

The Countdown Script

   
	using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
	
public class CountdownText : MonoBehaviour
{
public delegate void CountdownFinished();
public static event CountdownFinished OnCountdownFinished;
	Text countdown;
	void OnEnable()
{
countdown = GetComponent<Text>();
countdown.text = "3";
StartCoroutine("Countdown");
}
	IEnumerator Countdown()
{
int count = 3;
for (int i = 0; i < count; i++)
{
countdown.text = (count - i).ToString();
yield return new WaitForSeconds(1);
	}
OnCountdownFinished();
}
}
	


Crate Script

	sing UnityEngine;
	public class Crate : MonoBehaviour {
	public bool hit = false;
	void OnTriggerEntre2D(Collider2D collider)
{
if (collider.tag =="Player")
{
hit = true;
}
	}
	}
	

CrateSpawn Script

	using System.Collections;
using System.Collections.Generic;
using UnityEngine;
	public class CrateSpawn : MonoBehaviour {
	List<Cratework> cratePool;
int index = -1;
public GameObject cratePrefab;
public float spawnTime = 4f;
public float speed = 35;
public int poolSize = 5;
public bool isRunning = true;
	[HideInInspector]
public bool hit = false;
	void Start()
{
cratePool = new List<Cratework>();
for (int i = 0; i < poolSize; i++)
{
var crate = (GameObject)Instantiate(cratePrefab, new Vector3(0, 8, 0), Quaternion.identity);
cratePool.Add(crate.GetComponent<Cratework>());
}
StartCoroutine(SpawnCrate());
}
	void Update()
{
for (int i = 0; i <= poolSize; i++)
{
var crate = cratePool;
crate.transform.position += new Vector3(0, speed * Time.deltaTime, 0);
if (crate.hit)
{
hit = true;
StopAllCoroutines(SpawnCrate());
}
}
}
	IEnumerator SpawnCrate()
{
while (isRunning)
{
index++;
index %= poolSize;
	var crate = cratePool[index];
float x = Random.Range(-2, 2);
crate.transform.position = new Vector3(x, -6, 0);
	yield return new WaitForSeconds(spawnTime);
}
	}
}
	

CrateWork Script

	using UnityEngine;
	public class Cratework : MonoBehaviour {
	public Crate left;
public Crate right;
	public bool hit = false;
	void Update ()
{
if (left.hit || right.hit)
{
hit = true;
}
}
}
	

GameController Script

	using System.Collections;
using System.Collections.Generic;
using UnityEngine;
	public class GameController : MonoBehaviour {
public CrateSpawn crateSpawn;
	void ChangeSpeed(float speed)
{
crateSpawn.speed = speed;
}
	void Update()
{
if (crateSpawn.hit)
{
ChangeSpeed(0);
}
}
}
	

GameManager Script

	using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
	
public class GameManager : MonoBehaviour {
public delegate void GameDelegate();
public static event GameDelegate OnGameStarted;
public static event GameDelegate OnGameOverConfirmed;
	public static GameManager Instance;
	public GameObject startPage;
public GameObject gameOverPage;
public GameObject countdownPage;
public Text scoreText;
	enum PageState
{
None,
Start,
GameOver,
Countdown
}
	
int score = 0;
bool gameover = true;
	public bool GameOver { get { return gameover; } }
	void Awake()
{
Instance = this;
}
	void OnEnable()
{
CountdownText.OnCountdownFinished += OnCountdownFinished;
MoveController.OnPlayerDied += OnPlayerDied;
MoveController.OnPlayerScored += OnPlayerScored;
}
	void OnDisable()
{
CountdownText.OnCountdownFinished -= OnCountdownFinished;
MoveController.OnPlayerDied -= OnPlayerDied;
MoveController.OnPlayerScored -= OnPlayerScored;
	}
	void OnCountdownFinished()
{
SetPageState(PageState.None);
OnGameStarted();
score = 0;
gameover = false;
}
	void OnPlayerDied()
{
gameover = true;
int savedScore = PlayerPrefs.GetInt("HighScore");
if (score > savedScore)
{
PlayerPrefs.SetInt("HighScore", score);
}
SetPageState(PageState.GameOver);
}
	void OnPlayerScored()
{
score++;
scoreText.text = score.ToString();
}
	void SetPageState(PageState state)
{
switch (state)
{
case PageState.None:
startPage.SetActive(false);
gameOverPage.SetActive(false);
countdownPage.SetActive(false);
break;
case PageState.Start:
startPage.SetActive(true);
gameOverPage.SetActive(false);
countdownPage.SetActive(false);
break;
case PageState.GameOver:
startPage.SetActive(false);
gameOverPage.SetActive(true);
countdownPage.SetActive(false);
break;
case PageState.Countdown:
startPage.SetActive(false);
gameOverPage.SetActive(false);
countdownPage.SetActive(true);
break;
}
}
	public void ConfirmGameOver()
{
OnGameOverConfirmed();//event
scoreText.text = "0";
SetPageState(PageState.Start);
}
	public void StartGame()
{
SetPageState(PageState.Countdown);
}
	}
	

HighScore Script

	using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
	
public class HighscoreText : MonoBehaviour
{
	Text highscore;
	void OnEnable()
{
highscore = GetComponent<Text>();
highscore.text = ": " + PlayerPrefs.GetInt("HighScore").ToString();
}
}
	

MoveController Script

	using System.Collections;
using System.Collections.Generic;
using UnityEngine;
	public class MoveController : MonoBehaviour {
	public delegate void PlayerDelegate();
public static event PlayerDelegate OnPlayerDied;
public static event PlayerDelegate OnPlayerScored;
	public float speed = 0.25f;
public Vector3 startPos;
	Rigidbody2D rigidbody;
GameManager game;
	void Start()
{
rigidbody = GetComponent<Rigidbody2D>();
game = GameManager.Instance;
}
	void OnEnable()
{
GameManager.OnGameStarted += OnGameStarted;
GameManager.OnGameOverConfirmed += OnGameOverConfirmed;
	}
	void OnDisable() 
{
GameManager.OnGameStarted -= OnGameStarted;
GameManager.OnGameOverConfirmed -= OnGameOverConfirmed;
}
	void OnGameStarted()
{
rigidbody.velocity = Vector3.zero;
rigidbody.simulated = true;
}
	void OnGameOverConfirmed()
{
transform.localPosition = startPos;
}
	void Update()
{
transform.Translate(Input.acceleration.x * speed, 0, 0);
	}
	void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "ScoreZone")
{
OnPlayerScored();
//play a sound 
//get a point
}
	if (col.gameObject.tag == "DeadZone")
{
OnPlayerDied();
rigidbody.simulated = false;
	}
}
}
	

Share this post


Link to post
Share on other sites
Advertisement

Your code doesn't compile so I can see it isn't a direct copy/paste. I've got some ideas based on what you posted.

The first thing I notice is that your call to StopAllCoroutines() looks odd and doesn't compile. According to the docs it doesn't take a parameter. Fixing that may help.

You might modify the coroutine to test against the hit value directly, and terminate itself if the value is set. That way it isn't relying on other code to turn it off.

Do your prefab crates also have spawners in them? Do you have multiple objects or unexpected objects with spawners attached? Those might also cause issues.

If those don't address it, use your debugger to drop a breakpoint in CrateSpawn.Update() where you test against a hit.  There may be something wrong there where no crates get the value hit.

Share this post


Link to post
Share on other sites

Go slow on me lol I'm new to this im starting off with a simple project but i'm stuck i did not understand a word that you told me lol 

all i can tell you is that my crates spawn perfectly but i don't know why they don't stop when i collide with them someone told to do a breakpoint but i don't know what that means or what it is. if you could explain it would help me a lot...     

Share this post


Link to post
Share on other sites

Okay, stepping back a bit for those.

Debugging in Unity depends a little on if you are using Visual Studio or MonoDevelop.  Visual Studio tutorials are here, MonoDevelop are here.

Breaking down each of the recommendations a little more:

17 hours ago, frob said:

Your code doesn't compile so I can see it isn't a direct copy/paste. ... The first thing I notice is that your call to StopAllCoroutines() looks odd and doesn't compile. According to the docs it doesn't take a parameter. Fixing that may help.

When I copy your code to source files it does not compile.  Your CrateSpawn script was one of those.  I'm not sure if it was just an issue in how you pasted it to the forums, or if your code is not set up properly and it isn't being compiled inside Unity, or something else.  

Since StopAllCoroutines() should stop the SpawnCrate coroutine, that's the first think I'd make sure is compiling correctly. 

Following the tutorials up above on using the debugger, I'd set a breakpoint on that line in CrateSpawn with the StopAllCoroutines just to make sure it is being compiled, and to see if it is actually being hit.

17 hours ago, frob said:

You might modify the coroutine to test against the hit value directly, and terminate itself if the value is set. That way it isn't relying on other code to turn it off.

This suggestion is to not use StopAllCoroutines() at all. Instead, inside your SpawnCrate coroutine, you could add a test like:

if(hit)
  yield break;

That way you aren't depending on the Update() function to terminate the loop as an outside source. Instead you can exit the loop from within the loop code directly, which is usually considered a cleaner implementation.  You can see directly what ends the loop rather than hoping some external code ends the loop.

17 hours ago, frob said:

Do your prefab crates also have spawners in them? Do you have multiple objects or unexpected objects with spawners attached? Those might also cause issues.

Sometimes people will accidentally create more than one instance of things.  Instead of having 1 spawner, you may have accidentally created five or ten or more, but because they overlap you don't realize it.  Shutting off the main one won't shut off all the other ones.

Setting a breakpoint as described in the debugger tutorials above can help identify it.  If there are no more spawners running, the code should not be executed any more. You should be able to set a breakpoint but the debugger will not stop on it because the code is no longer running.

17 hours ago, frob said:

If those don't address it, use your debugger to drop a breakpoint in CrateSpawn.Update() where you test against a hit.  There may be something wrong there where no crates get the value hit.

Setting the breakpoint on Update() using those same methods above should let you see what is happening every time through the Update() loop if the object is active. You could then use the debugger to step through the code one line at a time. You could then look at the value of each variable to ensure the values are what you expect.

For example, maybe you thought hit should be true but really was false. Then you can set breakpoints at every line where hit gets assigned a value, both set to true and set to false. Then you can monitor that it is being set correctly in the first place, or you may discover it is not being set even though you thought it should be.  In the latter case you set a breakpoint right before it should have been set and see if those conditions are true.  Repeat at dividing the problem until you find the code that isn't working as expected.

Share this post


Link to post
Share on other sites

i left the scripts below so you can see what i have down because i what to finish this project. i got some problems:

1- i want the crates to start spawning after i hit start 

2- i also want when the player collides with the crate the crates will stop spawning and  when i hit the reset the the game will start over.

when i hit play in unity the crates start spawning even if i dont hit the start button if i collide  with the crate it says GAMEOVER but the crates keep on spawning. LOL 

i know that your trying to help and a appreciate that i really do but like i said before i'm new to this. 

take a look at the scripts i know the scripts above got all messed up please and thanks for helping ...

 

MoveController.cs

HighscoreText.cs

GameManager.cs

GameController.cs

Cratework.cs

CrateSpawn.cs

Crate.cs

CountdownText.cs

Edited by dell96

Share this post


Link to post
Share on other sites

I'm out traveling and don't have my dev machine available, I was hoping someone else would have chimed in by now.

On a quick reading of the file, I think your crate.cs function  OnTirggerEntre2D() is wrong.  Replace it with OnTriggerEnter2D(), and use a breakpoint to make certain the code is being called.  I also I don't see anything in the code that kills the SpawnCreate() coroutine, but it might have the value set somewhere in some other script.

Share this post


Link to post
Share on other sites

alright i try that!!, I we be writing to tell you what happens thank you for helping me, hope that your trip goes as planned.

  

Share this post


Link to post
Share on other sites

IT WORKED !!!!!!!   thanks omg thank you 

 

now i have to make it restart when i hit restart 

 

but thank you 

 

Edited by dell96

Share this post


Link to post
Share on other sites

what should i do to make my crate spawn again when i hit start button got any ideas that may help @frob because now you help me fix my last problem when the player hit my crate stop then my GAMEOVER page loads it has a reset button and that load the start page so i can hit the start button  but then the crates wont spawn open to any ideas....  please and thank you 

Share this post


Link to post
Share on other sites

  • Advertisement
  • Advertisement
  • Popular Tags

  • Similar Content

    • By Alexander_Vovk
      Hello Guys!
      Please share your experience, where is it better to find sales manager  specialists for indie team of 6 + people(remotely)?
      Maybe someone has a good experience of cooperation with finding projects through sale managers(USA and Canada)?
      Thank you
      Best Regards
      Alex Vovk
      Co-Founder of Sixteen Squares
      Alexander_Vovk@outlook.com
       
    • By RoKabium Games
      Been a bit quiet recently, but we've been busy bug fixing and tweaking things... Now we have lots more 'Particle effects' in the game, specifically here the Flamethrower and Enemy attacks!
    • By JoshuaFraser
      Hi and thanks for reading, I have an issue with this reactive crosshair script, everything works fine until I start changing the offset. Give the script a go and you will see what I mean, when I do SetOffset(0f); it doesnt always set back to the origional state, if anyone can spot a fix I'd be super appreciative!
      using System.Collections; using System.Collections.Generic; using UnityEngine; public class ReactiveCrosshair : MonoBehaviour { [SerializeField] GameObject c_limb_prefab; private float center_offset = 0f; private float current_offset = 0f; private float max_offset = .5f; private int number_of_limbs = 4; private float limb_length = .05f; private float limb_width = .005f; private List<GameObject> c_limbs = new List<GameObject>(); public void SetupCrosshair(){ for (int i = 0; i < number_of_limbs; i++) { GameObject line_go = (GameObject)Instantiate (c_limb_prefab); line_go.transform.SetParent (this.transform); Vector3 limb_pos = new Vector3 (0f,0f,0f); //line_go.transform.position = limb_pos; line_go.transform.localPosition = limb_pos; LineRenderer line = line_go.GetComponent<LineRenderer>(); line.startWidth = limb_width; line.positionCount = 2; line.SetPosition (0, line_go.transform.localPosition + new Vector3(center_offset, 0f, 0f)); line.SetPosition (1, line_go.transform.localPosition + new Vector3(center_offset + limb_length, 0f, 0f)); line.useWorldSpace = false; c_limbs.Add(line_go.gameObject); } if (c_limbs != null) { OrientLimbs (); SetOffset (0f); } } public void OrientLimbs(){ for (int i = 0; i < c_limbs.Count; i++) { float rotation_step = 360f / (float)c_limbs.Count; c_limbs [i].transform.RotateAround (c_limbs[i].transform.position, c_limbs[i].transform.forward, 90f + (rotation_step * (float)i)); } } public void SetOffset(float _current_spread){ float offset = Mathf.Lerp (0f, max_offset, _current_spread); for (int i = 0; i < number_of_limbs; i++) { if (offset > current_offset) { Vector3 pos = c_limbs [i].transform.position + (c_limbs [i].transform.TransformDirection (Vector3.right) * offset); c_limbs [i].transform.position = pos; } if (offset < current_offset) { Vector3 pos = c_limbs [i].transform.position - (c_limbs [i].transform.TransformDirection (Vector3.right) * offset); c_limbs [i].transform.position = pos; } } Debug.Log ("SetOffset() offset: " + offset.ToString () + " _current_spread: " + _current_spread.ToString() + " localPos: " + c_limbs[1].transform.localPosition); current_offset = offset; } }  
    • By Erik Nivala
      So, as the title says i am trying to figure out a good way sync all that information with other players in Unity. My problem is that i can't come up with a good solution since i am used to creating classes for everything e.g. attachments are its own class and then the weapon would save a reference to that attachment. But since you can't send custom classes over [Command] & [ClientRPC] i am a little stuck. A solution for this would be giving each attachment for a slot a unique ID and then passing the ID to other player but i feel like that is very error prone if other ppl add a new attachment or the IDs get mixed up.
      Is there a "standard" way that this is usually done that i am missing?
      I am fairly new to programming so any help is appreciated!
    • By MintyLyton
      I'm looking for any team / people that need a programmer for their project. I'm looking to expand my portfolio which you can see Here. I'm more experienced with Unity but I can spend the time to learn new Engines if that's your preference. I have worked on Unreal Engine 4 before but I might take some time to re-learn it, if the project requires it. Feel free to DM here or use the contact info on my website. 
    • By Woody Stevens
      Hi,
       
      I am looking for a TCP or HTTP networking library similar to Lidgren (UDP).
       
      This is primarily for sending game map data and potentially other large messages from Server to Client.
       
      I do want to keep Lidgren for my chat messages, player position, small fast updates etc. I especially love the flow of data and the library usage in general, so any libraries of a similar style would be excellent. Preferably something open source, free and reliable.
      I also must be able to swap between localhost and an ip address with ease, like Lidgren, as I run a server for singleplayer/mp/lan.
       
      My game maps are similar to minecraft, but it is 2d and only one Z-level, so i'm sending a jagged array of Tile object data (currently only enum TileID.Grass) down the pipe to the Client. Problem is if i'm sending a large map 1024 x 1024 tiles down the to client that's quite a lot of data, and Lidgren is relatively slow to build the writes (before the message is even sent!). It is fine when i'm using smaller maps < 512 x 512 ( xTiles * yTiles ).

      I know about chunking and will look into implementing this later, whilst taking into account the user's position in the world to only send nearby chunks.
       
      An example of my code that can be slow:
      private void WriteWorld(NetOutgoingMessage outgoing) { try { var world = WorldManager.Instance.CurrentWorld; outgoing.Write(world.XTiles); outgoing.Write(world.YTiles); for (int x = 0; x < world.XTiles; x++) { for (int y = 0; y < world.YTiles; y++) { // Write Tile obj data outgoing.Write((int)world.Tiles[x][y]); // <-------- Slow here when xTiles and yTiles are each > 512 ! } } } catch (Exception ex) { // log send error } }  
      I'd love to hear from you guys, especially if any of you have come across a similar challenge.
    • By ethancodes
      I'm working on a system for my game that will allow the player to stack pick ups in a queue. As one pick up expires, the next automatically activates. I'm having an issue though where if I pick up the first one, it activates fine, but if i pick up a second directly after it, it overrides the first one, activates the second one, and then once it has run it's course, everything goes back to normal gameplay, no first pick up. I'm not sure why this is happening. Hopefully someone can spot what I'm doing wrong in my code.
      Here is the code for the pick up manager:
      // Update is called once per frame void Update () { if (pickUpQueue.Count != 0 && !pickUpActive) { pickUpActive = true; pickUpQueue[0].ActivatePickUp(); } DeactivatePickUp(); } void DeactivatePickUp () { if (pickUpQueue.Count != 0 && pickUpActive) { Destroy (pickUpQueue [0]); pickUpQueue.RemoveAt (0); pickUpActive = false; } } And here is the PickUp:
      public override void ActivatePickUp () { ball.GetComponent<Ball>().Speed = 2.0f; //increase ball speed... ball.GetComponent<Ball>().StartCoroutine(timer); //...set time that power up is active }  
      There is also a Base Pick Up:
      public void OnCollisionEnter2D (Collision2D collision) { Vector2 tweak = new Vector2 (Random.Range(0f, 0.2f),Random.Range(0f, 0.2f)); this.gameObject.GetComponent<Rigidbody2D>().velocity += tweak; //if the pickup makes contact with the paddle or ball.... if (collision.gameObject.tag == "Paddle" || collision.gameObject.tag == "Ball") { GameObject.FindObjectOfType<GameManager>().GetComponent<PickUpManager>().pickUpQueue.Add(this); Destroy(gameObject); //...and finally destroy power up object } } As a side note, I am trying to find a solution to this that will work for all of my pickups. Some pickups are ammo based, some are timed. 
    • By Hellados
      Hello guys, my name is Giorgi and i'm newbie game developer i'm learning Pixel art and after pixel art  i want learn C# and don't know how and where start i'm bad with programming language and know only HTML/CSS
  • Advertisement
  • Popular Now

  • Forum Statistics

    • Total Topics
      631396
    • Total Posts
      2999789
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!