public class green : MonoBehaviour
{
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "BLUE")
{
Destroy(other.gameObject);
gm.mylife -= 1;
}
}
}
public class gm : MonoBehaviour
{
public GameObject blue;
static public bool tr = false;
public Text life;
public static int mylife = 0;
void Start()
{
makebox();
}
void makebox()
{
StartCoroutine("timedelay");
}
IEnumerator timedelay()
{
yield return new WaitForSeconds(3f);
Debug.Log("sdfaDF");
GameObject br = Instantiate(blue, new Vector3(-6, -2, 0), Quaternion.identity) as GameObject;
makebox();
}
void Update()
{
life.text = (mylife.ToString());
}
}
I made a blue box which is destroyed when it meets something and has -1 score.
And it is made at (-2,2)position .
Then I made a prefab. But the prefab does not work as its origin. It is JUST created at the same position as its origin.
I want to make my prefab destroy and score -1 also.
How can i fix it ?
PLEASE HELP ME...
You are spawning the object at same position all the time:
GameObject br = Instantiate(blue, new Vector3(-6, -2, 0), Quaternion.identity) as GameObject;
Instead you should give a new position every time like this:
public Vector3 offSet = new Vector3(2,0,0);
Vector3 pos;
IEnumerator timedelay()
{
yield return new WaitForSeconds(3f);
Debug.Log("sdfaDF");
GameObject br = Instantiate(blue, pos, Quaternion.identity) as GameObject;
pos += offSet;
makebox();
}
GameObject blue = Instantiate(bluep);
blue.tag = "BLUE";
I solved by giving tag to the object at the script.
Related
I apologize for the block of code below but I am not sure where the issue is. I am trying to get a laser to appear off screen and attempt to hit the player. I have no idea why this code does nothing. It is most likey just a stupid mistake I have made.
`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Lasers : MonoBehaviour
{
private LineRenderer lr;
public bool Above = true;
public bool Below = false;
public bool Left = false;
public bool Right = false;
public Transform LaserStartPoint;
public Transform LaserEndPoint;
public Transform Player;
public float LaserWidth = 0.75f;
public float LaserLength = 19f;
public float LaserDuration = 0.5f;
public float LaserFadeDuration = 0.5f;
public GameObject Laser;
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
ShootLaser();
}
}
void ShootLaser()
{
if(Above)
{
LaserStartPoint.position = new Vector3(Random.Range(-10,10), 6, -1);
}
if(Below)
{
LaserStartPoint.position = new Vector3(Random.Range(-10,10), -6, -1);
}
if(Left)
{
LaserStartPoint.position = new Vector3(-10, Random.Range(-6,6), -1);
}
if(Right)
{
LaserStartPoint.position = new Vector3(10, Random.Range(-6,6), -1);
}
Instantiate(Laser, LaserStartPoint.position, Quaternion.identity);
lr = Laser.GetComponent<LineRenderer>();
lr.startWidth = LaserWidth;
lr.endWidth = LaserWidth;
lr.positionCount = 2;
Vector3 dir = Player.position - LaserStartPoint.position;
LaserEndPoint.position = LaserStartPoint.position + dir.normalized * LaserLength;
lr.SetPosition(0, LaserStartPoint.position);
lr.SetPosition(1, LaserEndPoint.position);
Invoke("FadeLaser", LaserDuration);
}
void FadeLaser()
{
lr.startColor = Color.Lerp(lr.startColor, Color.clear, LaserFadeDuration);
lr.endColor = Color.Lerp(lr.endColor, Color.clear, LaserFadeDuration);
Laser.SetActive(false);
}
}
`
I have looked in the Hierarchy and nothing is spawning. None of the values are changing on the Script. I have the script attached to the main camera and it spawns in my LaserLineRenderer prefab.
You are attempting to modify the line renderer component of the prefab. You need to grab the reference of the instantiated object when it is spawned in.
private GameObject instantiatedLazer;
/*In ShootLaser function*/
instantiatedLazer = Instantiate(Laser, LaserStartPoint.position, Quaternion.identity);
lr = instantiatedLazer.GetComponent<LineRenderer>();
/*In FadeLaser function*/
instantiatedLazer.SetActive(false);
Hi im trying to convert a code that work on 3D project to get gameobject which i click on my mouse to work on 2D since im now doing a 2D project
public class SetTower : MonoBehaviour {
public int selected;
public GameObject[] towers;
public float[] prices;
public GameObject tile;
private Money moneyScript;
// Use this for initialization
void Start ()
{
moneyScript = GameObject.Find("GameLogic").GetComponent<Money>();
}
// Update is called once per frame
void Update ()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 20))
{
if(hit.transform.tag == "Tile")
{
tile = hit.transform.gameObject;
}
else
{
tile = null;
}
if (Input.GetMouseButtonDown(0) && tile != null)
{
TileTaken tileScript = tile.GetComponent<TileTaken>();
if(!tileScript.isTaken && moneyScript.money >= prices[selected])
{
moneyScript.money -= prices[selected];
Vector2 pos = new Vector2(tile.transform.position.x, tile.transform.position.y);
tileScript.tower = (GameObject)Instantiate(towers[selected], pos, Quaternion.identity);
tileScript.isTaken = true;
}
}
}
}
}
Replace Camera.main.ScreenPointToRay with Camera.main.ScreenToWorldPoint, Physics.Raycast with Physics2D.Raycast, and RaycastHit with RaycastHit2D. Make sure to also switch to 2D Colliders. For example, Box Collider should be replaced with Box Collider 2D.
public class SetTower : MonoBehaviour
{
public int selected;
public GameObject[] towers;
public float[] prices;
public GameObject tile;
private Money moneyScript;
// Use this for initialization
void Start()
{
moneyScript = GameObject.Find("GameLogic").GetComponent<Money>();
}
// Update is called once per frame
void Update()
{
Vector2 ray = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(ray, Vector2.zero, 20);
if (hit)
{
if (hit.transform.tag == "Tile")
{
tile = hit.transform.gameObject;
}
else
{
tile = null;
}
if (Input.GetMouseButtonDown(0) && tile != null)
{
TileTaken tileScript = tile.GetComponent<TileTaken>();
if (!tileScript.isTaken && moneyScript.money >= prices[selected])
{
//moneyScript.money -= prices[selected];
Vector2 pos = new Vector2(tile.transform.position.x, tile.transform.position.y);
//tileScript.tower = (GameObject)Instantiate(towers[selected], pos, Quaternion.identity);
//tileScript.isTaken = true;
}
}
}
}
}
I have made a breakout game using unity tutorials and everything seemed to work well, but when I played it in the game mode there were some errors. So after I tried fixing the errors, the bricks wont get destroyed anymore. I tried undoing it, writing the code anew or even writing the same project anew but nothing works. What can I do?
These are the codes for my game which are exactly like the codes in the tutorial!
Paddle:
public class Paddle : MonoBehaviour {
public float paddleSpeed = 1f;
private Vector3 playerPos = new Vector3(0, -9f, 0);
void Update ()
{
float xPos = transform.position.x + (Input.GetAxis("Horizontal")*paddleSpeed);
playerPos = new Vector3(Mathf.Clamp(xPos, -7.5f, 7.5f), -9f, 0f);
transform.position = playerPos;
}
}
Ball:
public class Ball : MonoBehaviour {
private float ballInitialVelocity = 600f;
private Rigidbody rb;
private bool ballInPlay;
void Awake ()
{
rb = GetComponent<Rigidbody>();
}
void Update ()
{
if(Input.GetButtonDown("Fire1") && ballInPlay==false)
{
transform.parent = null;
ballInPlay = true;
rb.isKinematic = false;
rb.AddForce(new Vector3(ballInitialVelocity, ballInitialVelocity, 0));
}
}
}
GM:
using UnityEngine; using System.Collections;
public class deathZone : MonoBehaviour {
void OnTriggerEnter(Collider col)
{
GM.instance.loseLife();
}
}
public class GM : MonoBehaviour {
public int Lives = 3;
public int bricks = 16;
public float resetDelay = 1f;
public Text livesText;
public GameObject gameOver;
public GameObject bricksPrefab;
public GameObject youWon;
public GameObject paddle;
public GameObject deathParticles;
public static GM instance = null;
private GameObject clonePaddle;
void Start()
{
if (instance == null)
instance = this;
else if (instance != this)
instance = null;
setup();
}
public void setup()
{
clonePaddle = Instantiate(paddle, new Vector3(0, -9,0), Quaternion.identity) as GameObject;
Instantiate(bricksPrefab, new Vector3((float)18.5, (float)-61.14095, (float)238.4855), Quaternion.identity);
}
void checkGameOver()
{
if (bricks < 1)
{
youWon.SetActive(true);
Time.timeScale = .25f;
Invoke("Reset", resetDelay);
}
if (Lives < 1)
{
gameOver.SetActive(true);
Time.timeScale = .25f;
Invoke("Reset", resetDelay);
}
}
void Reset()
{
Time.timeScale = 1f;
Application.LoadLevel(Application.loadedLevel);
}
public void loseLife()
{
Lives--;
livesText.text = "Lives: " + Lives;
Instantiate(deathParticles, clonePaddle.transform.position, Quaternion.identity);
Destroy(clonePaddle);
Invoke("SetupPaddle", resetDelay);
checkGameOver();
}
void SetupPaddle()
{
clonePaddle = Instantiate(paddle, new Vector3(0, -9, 0), Quaternion.identity) as GameObject;
}
public void destroyBrick()
{
bricks--;
checkGameOver();
}
}
Bricks:
public class Bricks : MonoBehaviour {
public GameObject brickParticle;
void OnCollisionEnter(Collision other)
{
Instantiate(brickParticle, transform.position, Quaternion.identity);
GM.instance.destroyBrick();
Destroy(gameObject);
}
}
deathZone:
public class deathZone : MonoBehaviour {
void OnTriggerEnter(Collider col)
{
GM.instance.loseLife();
}
}
In this tutorial you have to make sure all of the bricks GameObject have both the Bricks script and a BoxCollider components. Also the ball should have a Rigidbody and a SphereCollider components.
An easy way to debug Collisions or Triggers is to simply use a Debug.Log("something"); as a first command in the OnCollisionEnter/OnTriggerEnter/... methods.
It seems that the issue is with colliders. You should check them in Editor if they are placed right ( since no debug.log on collision is written). Also make sure that you are using Colliders and not colliders2D ( collision is called by diffrent method)
so I was wondering if there was a way to make a spawned object gradually moves/go faster after the player (you the user) collects 10 points. And faster when the player collects another 10 points and so on and so on?
This is my movement script attach to my objects that get spawned in:
public class Movement : MonoBehaviour
{
public static int movespeed = 20;
public Vector3 userDirection = Vector3.right;
public void Update()
{
transform.Translate(userDirection * movespeed * Time.deltaTime);
}
}
This is my score script attach to my player
public int Score;
public Text ScoreText;
void Start ()
{
Score = 0;
SetScoreText ();
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag ("Pick Up"))
{
other.gameObject.SetActive (false);
Score = Score + 1;
SetScoreText ();
}
}
void SetScoreText ()
{
ScoreText.text = "Score: " + Score.ToString ();
}
And this is my generateEnemy script:
public GameOverManager gameOverManager = null;
[HideInInspector]
public float minBlobSpawnTime = 2;
[HideInInspector]
public float maxBlobSpawnTime = 5;
[HideInInspector]
public bool generateBlobs = true;
[HideInInspector]
public GameObject blobPrefab = null;
[HideInInspector]
public GameObject blobRoot = null;
[HideInInspector]
public float minimumYPosition = -0.425f;
[HideInInspector]
public float maximumYPosition = 0.35f;
[HideInInspector]
public float minDaggerSpawnTime = 2;
[HideInInspector]
public float maxDaggerSpawnTime = 5;
[HideInInspector]
public bool generateDaggers = true;
[HideInInspector]
public GameObject daggerPrefab = null;
[HideInInspector]
public GameObject daggerRoot;
[HideInInspector]
public float minimumXPosition = -11.5f;
[HideInInspector]
public float maximumXPosition = 11.5f;
public Camera camera = null;
// Use this for initialization
void Start ()
{
generateBlobs = ((generateBlobs) && (blobPrefab != null) && (blobRoot != null));
generateDaggers = ((generateDaggers) && (daggerPrefab != null) && (daggerRoot != null));
if (camera == null)
{
Debug.LogError("GenerateEnemy: camera is not set in the inspector. Please set and try again.");
camera = Camera.main;
}
if (gameOverManager == null)
{
Debug.LogError("GenerateEnemy: gameOverManager not set in the inspector. Please set and try again.");
}
if (generateBlobs)
{
StartCoroutine(GenerateRandomEnemy(true, blobPrefab, blobRoot, minBlobSpawnTime, maxBlobSpawnTime));
}
if (generateDaggers)
{
StartCoroutine(GenerateRandomEnemy(false, daggerPrefab, daggerRoot, minDaggerSpawnTime, maxDaggerSpawnTime));
}
}
// Update is called once per frame
void Update ()
{
DestroyOffScreenEnemies();
}
// Spawn an enemy
IEnumerator GenerateRandomEnemy(bool generateOnYAxis, GameObject prefab, GameObject root, float minSpawnTime, float maxSpawnTime)
{
if ((prefab != null) && (gameOverManager != null))
{
if (!gameOverManager.GameIsPaused())
{
GameObject newEnemy = (GameObject) Instantiate(prefab);
newEnemy.transform.SetParent(root.transform, true);
// set this in the prefab instead
// newEnemy.transform.position = new Vector3(newEnemy.transform.parent.position.x, 0.5f, newEnemy.transform.parent.position.z);
// or if you want the y position to be random you need to do something like this
if (generateOnYAxis)
{
newEnemy.transform.position = new Vector3(newEnemy.transform.parent.position.x, Random.Range(minimumYPosition, maximumYPosition), newEnemy.transform.parent.position.z);
}
else
{
newEnemy.transform.position = new Vector3(Random.Range(minimumXPosition, maximumXPosition), newEnemy.transform.parent.position.y, newEnemy.transform.parent.position.z);
}
}
}
yield return new WaitForSeconds(Random.Range(minSpawnTime, maxSpawnTime));
StartCoroutine(GenerateRandomEnemy(generateOnYAxis, prefab, root, minSpawnTime, maxSpawnTime));
}
public void DestroyOffScreenEnemies()
{
GameObject[] enemies = GameObject.FindGameObjectsWithTag("enemy");
if ((enemies.Length > 0) && (camera != null))
{
for (int i = (enemies.Length - 1); i >= 0; i--)
{
// just a precaution
if ((enemies[i] != null) && ((camera.WorldToViewportPoint(enemies[i].transform.position).x > 1.03f) ||
(enemies[i].transform.position.y < -6f)))
{
Destroy(enemies[i]);
}
}
}
}
}
(This script has an generateEnemyCustomEditor script that references it, to show in the inspector)
Thank you :)
First of all, remove the static keyword from public static int movespeed = 20; and use GameObject.Find("ObjectMovementIsAttachedTo").GetComponent<Movement>(); to get the script instance if you want to modify movespeed variable from another script.
And faster when the player collects another 10 points and so on and so
on?
The solution is straight on. Use
if (Score % 10 == 0){
//Increement by number (4) movespeed from Movement script
movement.movespeed += 4;
}
to check if the Score is increased by 10 then increment movespeed by any value you want if that condition is true. It makes sense to put that in the OnTriggerEnter2D function after Score is incremented by 1.
Your new score script:
public class score : MonoBehaviour
{
public int Score;
public Text ScoreText;
private int moveSpeed;
void Start()
{
Score = 0;
SetScoreText();
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Pick Up"))
{
other.gameObject.SetActive(false);
Score = Score + 1;
if (Score % 10 == 0)
{
//Increement by number (4) movespeed from Movement script
moveSpeed += 4;
}
SetScoreText();
}
}
public int getMoveSpeed()
{
return moveSpeed;
}
void SetScoreText()
{
ScoreText.text = "Score: " + Score.ToString();
}
}
Since your Movement script will be instantiated, when you instantiate it, you send its reference to the Player script.
public class Movement : MonoBehaviour
{
public int movespeed = 20;
public Vector3 userDirection = Vector3.right;
score mySpeed;
void Start()
{
//Send Movement instance to the score script
GameObject scoreGameObject = GameObject.Find("GameObjectScoreIsAttachedTo");
mySpeed = scoreGameObject.GetComponent<score>();
}
public void Update()
{
transform.Translate(userDirection * mySpeed.getMoveSpeed() * Time.deltaTime);
}
}
I have a character who is able to shoot; however, when the character dies and respawns he is unable to shoot and I get the error:
UnassignedReferenceException: The variable BulletTrailPrefab of Weapon has not been assigned.
You probably need to assign the BulletTrailPrefab variable of the Weapon script in the inspector.
UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, Vector3 pos, Quaternion rot) (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/UnityEngineObject.cs:74)
UnityEngine.Object.Instantiate (UnityEngine.Object original, Vector3 position, Quaternion rotation) (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/UnityEngineObject.cs:84)
Weapon.Effect () (at Assets/Weapon.cs:64)
Weapon.Shoot () (at Assets/Weapon.cs:53)
Weapon.Update () (at Assets/Weapon.cs:33)
If someone can help me fixing this it would be greatly appreciated. I have tried lots of stuff however nothing appears to work.
My weapon script
using UnityEngine;
using System.Collections;
public class Weapon : MonoBehaviour {
public float fireRate = 0;
public float Damage = 10;
public LayerMask whatToHit;
public Transform target;
public Transform BulletTrailPrefab;
float timeToSpawnEffect = 0;
public float effectSpawnRate = 10;
float timeToFire = 0;
Transform firePoint;
float nextTimeToSearch = 0;
// Use this for initialization
void Awake () {
firePoint = transform.FindChild ("firePoint");
if (firePoint == null) {
Debug.LogError ("No firePoint? WHAT?!");
}
}
// Update is called once per frame
void Update () {
if (fireRate == 0) {
if (Input.GetButtonDown ("Fire1")) {
Shoot();
}
}
else {
if (Input.GetButton ("Fire1") && Time.time > timeToFire) {
timeToFire = Time.time + 1/fireRate;
Shoot();
}
}
if (target == null) {
FindBulletTrailPrefab ();
return;
}
}
void Shoot () {
Vector2 mousePosition = new Vector2 (Camera.main.ScreenToWorldPoint (Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
Vector2 firePointPosition = new Vector2 (firePoint.position.x, firePoint.position.y);
RaycastHit2D hit = Physics2D.Raycast (firePointPosition, mousePosition-firePointPosition, 100, whatToHit);
if (Time.time >= timeToSpawnEffect) {
Effect ();
timeToSpawnEffect = Time.time + 1/effectSpawnRate;
}
Debug.DrawLine (firePointPosition, (mousePosition-firePointPosition)*100, Color.cyan);
if (hit.collider != null) {
Debug.DrawLine (firePointPosition, hit.point, Color.red);
Debug.Log ("We hit " + hit.collider.name + " and did " + Damage + " damage.");
}
}
void Effect () {
Instantiate (BulletTrailPrefab, firePoint.position, firePoint.rotation);
}
void FindBulletTrailPrefab () {
if (nextTimeToSearch <= Time.time) {
GameObject searchResult = GameObject.FindGameObjectWithTag ("BulletTrail");
if (searchResult != null)
target = searchResult.transform;
nextTimeToSearch = Time.time + 0.5f;
}
}
}
My gamemaster script
using UnityEngine;
using System.Collections;
public class GameMaster : MonoBehaviour {
public static GameMaster gm;
void Start () {
if (gm == null) {
gm = GameObject.FindGameObjectWithTag ("GM").GetComponent<GameMaster>();
}
}
public Transform playerPrefab;
public Transform spawnPoint;
public int spawnDelay = 2;
public IEnumerator RespawnPlayer () {
Debug.Log ("TODO: Add waiting for spawn sound");
yield return new WaitForSeconds (spawnDelay);
Instantiate (playerPrefab, spawnPoint.position, spawnPoint.rotation);
Debug.Log ("TODO: Add Spawn Particles");
}
public static void KillPlayer (Player player) {
Destroy (player.gameObject);
gm.StartCoroutine (gm.RespawnPlayer());
}
}
My player script
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
[System.Serializable]
public class PlayerStats {
public int Health = 100;
}
public PlayerStats playerStats = new PlayerStats();
public int fallBoundary = -20;
void Update () {
if (transform.position.y <= fallBoundary)
DamagePlayer (9999999);
}
public void DamagePlayer (int damage) {
playerStats.Health -= damage;
if (playerStats.Health <= 0) {
GameMaster.KillPlayer(this);
}
}
}
Late answer for answering's sake! (Lovely!)
The reason it only happens after you respawn is because when you instantiate a new playerPrefab, the Weapon object (which presumably is part of your player prefab) does not have the assignments you had made in the editor—those assignments are only for the specific instances that were in the editor. You'll need to manually assign it at runtime in one of two ways:
1) When you respawn:
public IEnumerator RespawnPlayer () {
// ...
GameObject playerInstance = Instantiate (
playerPrefab,
spawnPoint.position,
spawnPoint.rotation) as GameObject;
Weapon weaponInstance = playerInstance.GetComponentInChildren<Weapon>;
weaponInstance.BulletTrailPrefab = /* prefab reference */;
// ...
}
2) In your Weapon script:
void Start () {
BulletTrailPrefab = /* prefab reference */;
}
But in either case you would have to have some way of referencing the prefab at runtime, such as putting a reference into the GameMaster script or using Resources.Load().
The error is quite clear. You have not assigned a prefab to your variable..
UnassignedReferenceException: The variable BulletTrailPrefab of Weapon
has not been assigned.
You probably need to assign the BulletTrailPrefab variable of the
Weapon script in the inspector.