Solved
"buddies" multiplying, can't find what's wrong with my script
so I'm following this old tutorial: https://www.youtube.com/watch?v=77zdOaUGguc but my background just keeps multiplying all over the place, crashing Unity if I don't stop the game fast enough. I've looked through the comments and made the changes that people there suggested but it's an old video so i doubt I'll get any answers if i ask there.
My script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(SpriteRenderer))]
public class Tiling : MonoBehaviour
{
public int offsetX = 2;
public bool hasARightBuddy = false;
public bool hasALeftBuddy = false;
public bool reverseScale = false;
private float spriteWidth = 0f;
private Camera cam;
private Transform myTransform;
void Awake()
{
cam = Camera.main;
myTransform = transform;
}
// Use this for initialization
void Start()
{
SpriteRenderer sRenderer = GetComponent<SpriteRenderer>();
spriteWidth = sRenderer.sprite.bounds.size.x;
}
// Update is called once per frame
void Update()
{
if (hasALeftBuddy == false || hasARightBuddy == false)
{
float camHorizontalExtend = cam.orthographicSize * Screen.width / Screen.height;
float edgeVisiblePositionRight = (myTransform.position.x + spriteWidth / 2) - camHorizontalExtend;
float edgeVisiblePositionLeft = (myTransform.position.x - spriteWidth / 2) + camHorizontalExtend;
if (cam.transform.position.x >= edgeVisiblePositionRight - offsetX && hasARightBuddy == false)
{
MakeNewBuddy(1);
hasARightBuddy = true;
}
else if (cam.transform.position.x <= edgeVisiblePositionLeft + offsetX && hasALeftBuddy == false) ;
}
MakeNewBuddy(-1);
hasALeftBuddy = true;
}
void MakeNewBuddy(int rightOrLeft)
{
Vector3 newPosition = new Vector3(myTransform.position.x + myTransform.localScale.x * spriteWidth * rightOrLeft, myTransform.position.y, myTransform.position.z);
Transform newBuddy = Instantiate(myTransform, newPosition, myTransform.rotation) as Transform;
if (reverseScale == true)
{
newBuddy.localScale = new Vector3(newBuddy.localScale.x * -1, newBuddy.localScale.y, newBuddy.localScale.z);
}
newBuddy.parent = myTransform;
if (rightOrLeft > 0)
{
newBuddy.GetComponent<Tiling>().hasALeftBuddy = true;
}
else
{
newBuddy.GetComponent<Tiling>().hasARightBuddy = true;
}
}
}
Answer by Rachens · Mar 15, 2018 at 06:44 AM
OK so I solved it. I didn't ever open the "else if", all i had to was:
else if (cam.transform.position.x <= edgeVisiblePositionLeft + offsetX && hasALeftBuddy == false)
{
MakeNewBuddy(-1);
hasALeftBuddy = true;
}
Follow this Question
Related Questions
Modification to Unity2D Roguelike 1 Answer
DllNotFoundException: Anima2D 0 Answers
Getting trouble in migrating the Unity IAP old version to new version of IAP in existing project 0 Answers
How To Generate Platforms Down Each other in a pattern with some different positions Unity 1 Answer
How to stick to an object when a button is pressed Unity 2d 0 Answers