Change Color 오브젝트를 눌러서 AddComponent를 누른뒤 이름을 검색해 찾아서 추가해도 된다.
스크립트는 머테리얼 생성과 마찬가지로 프로젝트창에서 우클릭을 한 뒤 생성해주면 된다.
기존에 있던 스크립트 내용을 지우고 아래의 스크립트를 넣어준다.
using UnityEngine;
public class ChangeColor : MonoBehaviour
{
// 색깔 바꾸려는 오브젝트
public GameObject target;
// 색깔들 등록
public Material grey;
public Material purple;
public Material yellow;
public void ColorChange(string _color)
{
if (_color == "grey")
{
target.GetComponent<MeshRenderer>().material = grey;
}
else if (_color == "purple")
{
target.GetComponent<MeshRenderer>().material = purple;
}
else if (_color == "yellow")
{
target.GetComponent<MeshRenderer>().material = yellow;
}
}
}
이제 오브젝트들을 제 자리에 넣어주자.
바꾸려는 대상 오브젝트를 Target에,
바꾸려는 색깔 머테리얼을 각각의 이름에 넣어준다.
이제는 버튼에 기능을 걸어줄 시간이다.
하이어라키창에 생성해둔 Canvas - Button으로 들어간 뒤 기능을 걸어준다.
위에 표시해둔 순서대로
1. + 버튼을 누른 뒤
2. ChangeColor 오브젝트를 드래그앤 드랍해주고
3. 이름을 써준다. 참고로 이름은
위에 동그라미가 쳐진곳에 적힌 이름이다.
만약 이름을 바꾸고싶다면 ChangeColor로 들어가서 동그라미가 쳐져있는 부분의 이름을 바꾸면 된다.
using UnityEngine;
public class ChangeColor : MonoBehaviour
{
// 색깔 바꾸려는 오브젝트
public GameObject target;
// 색깔들 등록
public Material grey;
public Material purple;
public Material yellow;
public void ColorChange(string _color)
{
if(_color == "grey")
{
// GetComponent<Material>() 로 들어가면 안 된다.
target.GetComponent<SkinnedMeshRenderer>().material = grey;
}
else if (_color == "purple")
{
target.GetComponent<SkinnedMeshRenderer>().material = purple;
}
else if (_color == "yellow")
{
target.GetComponent<SkinnedMeshRenderer>().material = yellow;
}
}
}
Sprite Renderer, Animator, Player Controller, Capsule Collider2D, Rigidbody 2D
<GroundHolder>
<SpawnManager>
<GameManager>
<Canvas>
<Score>
Text
<Button>
<BestScore>
Text
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
bool isJump = false;
bool isTop = false;
public float jumpHeight = 0;
public float jumpSpeed = 0;
Vector2 startPosition;
Animator animator;
void Start()
{
startPosition = transform.position;
animator = GetComponent<Animator>();
}
void Update()
{
if (GameManager.instance.isPlay)
animator.SetBool("run", true);
else
animator.SetBool("run", false);
if(Input.GetMouseButtonDown(0) && GameManager.instance.isPlay) // isPlay모드일 때 발동하도록., // 마우스입력감지
{
isJump = true;
}
else if(transform.position.y <= startPosition.y)
{
isJump = false;
isTop = false;
transform.position = startPosition;
}
if(isJump) //GetmouseButtonDown은 마우스 클릭시 한 번만 인식하므로 판정오류를 없애기 위해 바로 코드를 적지 않는 것.
{
if(transform.position.y <= jumpHeight - 0.1f && !isTop)
{
transform.position = Vector2.Lerp(transform.position, new Vector2(transform.position.x, jumpHeight), jumpSpeed * Time.deltaTime);
}
else
{
isTop = true;
}
if(transform.position.y > startPosition.y && isTop)
{
transform.position = Vector2.MoveTowards(transform.position, startPosition, jumpSpeed*Time.deltaTime);
}
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.CompareTag("Mob"))
{
GameManager.instance.GameOver();
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// 몹 프리팹이 활성화되면 화면 우측에서 시작해서 화면 좌측을 넘어가면 다시 비활성화 되는 코드
public class MobBase : MonoBehaviour
{
public float mobSpeed = 0;
public Vector2 StartPosition;
private void OnEnable()
{
transform.position = StartPosition;
}
void Update()
{
if(GameManager.instance.isPlay)
{
transform.Translate(Vector2.left * Time.deltaTime * GameManager.instance.gameSpeed);
if (transform.position.x < -6)
{
gameObject.SetActive(false);
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RespawnManager : MonoBehaviour
{
public List<GameObject> MobPool = new List<GameObject>();
public GameObject[] Mobs;
public int objCnt = 1;
void Awake()
{
for(int i = 0; i < Mobs.Length; i++)
{
for(int q = 0; q < objCnt; q++)
{
MobPool.Add(CreateObj(Mobs[i], transform));
}
}
}
void Start()
{
GameManager.instance.onPlay += PlayGame;
}
void PlayGame(bool isplay)
{
if (isplay)
{
for(int i = 0; i < MobPool.Count; i++)
{
if (MobPool[i].activeSelf)
MobPool[i].SetActive(false);
}
StartCoroutine(CreateMob());
}
else
StopAllCoroutines();
}
IEnumerator CreateMob()
{
yield return new WaitForSeconds(0.5f);
while(GameManager.instance.isPlay)
{
//MobPool[Random.Range(0, MobPool.Count)].SetActive(true);
MobPool[DeactiveMob()].SetActive(true);
yield return new WaitForSeconds(Random.Range(1f, 3f));
}
}
int DeactiveMob()
{
List<int> num = new List<int>();
for(int i = 0; i < MobPool.Count; i++)
{
if (!MobPool[i].activeSelf) // 비활성된 녀석을 찾아 활성화시킨다.
num.Add(objCnt);
}
int x = 0;
if (num.Count > 0)
x = num[Random.Range(0, num.Count)];
return x;
}
GameObject CreateObj(GameObject obj, Transform parent)
{
GameObject copy = Instantiate(obj);
copy.transform.SetParent(parent);
copy.SetActive(false);
return copy;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GroundScroller : MonoBehaviour
{
public SpriteRenderer[] tiles;
public Sprite[] groundImg;
public float speed;
void Start()
{
temp = tiles[0];
}
SpriteRenderer temp;
void Update()
{
if(GameManager.instance.isPlay)
{
for (int i = 0; i < tiles.Length; i++)
{
if (-5 >= tiles[i].transform.position.x) // 타일 x좌표가 -5보다 작으면,
{
// 가장 뒤에 있는 타일을 검색하는 방법은 변수를 하나 두고 반복문과 배열을 이용하여 현재 타일 변수보다 x가 크면 현재 타일을 초기화해주면 된다.
for (int q = 0; q < tiles.Length; q++)
{
if (temp.transform.position.x < tiles[q].transform.position.x)
{
temp = tiles[q];
}
}
tiles[i].transform.position = new Vector2(temp.transform.position.x + 1, -0.3f);
tiles[i].sprite = groundImg[Random.Range(0, groundImg.Length)];
}
}
for (int i = 0; i < tiles.Length; i++)
{
tiles[i].transform.Translate(new Vector2(-1, 0) * Time.deltaTime * GameManager.instance.gameSpeed);
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
#region instance
public static GameManager instance;
private void Awake()
{
if(instance != null)
{
Destroy(gameObject);
return;
}
instance = this;
}
#endregion
public delegate void OnPlay(bool isplay);
public OnPlay onPlay;
public float gameSpeed = 1;
public bool isPlay = false;
public GameObject playBtn;
public Text bestScoreTxt;
public Text scoreTxt;
public int score = 0;
private void Start()
{
bestScoreTxt.text = PlayerPrefs.GetInt("BestScore", 0).ToString();
}
IEnumerator AddScore()
{
while(isPlay)
{
score++;
scoreTxt.text = score.ToString();
gameSpeed = gameSpeed + 0.01f;
yield return new WaitForSeconds(0.1f); // 0.1초마다 스코어를 1씩 더해준다.
}
}
public void PlayBtnClick()
{
playBtn.SetActive(false);
isPlay = true;
onPlay.Invoke(isPlay);
score = 0;
scoreTxt.text = score.ToString();
StartCoroutine(AddScore()); //코루틴 시작!
}
public void GameOver()
{
playBtn.SetActive(true);
isPlay = false;
onPlay.Invoke(isPlay);
StopCoroutine(AddScore());
if(PlayerPrefs.GetInt("BestScore", 0) < score)
{
PlayerPrefs.SetInt("BestScore", score);
bestScoreTxt.text = score.ToString();
}
}
}
Changes the time at which a sound that has already been scheduled to play will end. Notice that depending on the timing not all rescheduling requests can be fulfilled.
콘텐츠 크기 피터는 자체 레이아웃 요소의 크기를 제어하는 레이아웃 컨트롤러의 기능을 수행합니다. 크기는 게임 오브젝트의 레이아웃 요소 컴포넌트에서 제공하는 최소 또는 기본 크기에 따라 결정됩니다. 레이아웃 요소는 Image 또는 Text 컴포넌트이거나, 레이아웃 그룹이거나, Layout Element 컴포넌트일 수 있습니다.
사각 트랜스폼의 크기를 콘텐츠 크기 피터 등으로 조정하는 경우 피벗을 중심으로 크기가 조정되므로 피벗을 사용하여 크기 조정 방향을 제어할 수 있다는 점을 기억하면 유용할 수 있습니다.
예를 들어 피벗이 중앙에 있는 경우 콘텐츠 크기 피터에서 사각 트랜스폼을 모든 방향으로 균등하게 확장합니다. 그리고 피벗이 왼쪽 상단 모서리에 있는 경우 콘텐츠 크기 피터에서 사각 트랜스폼을 오른쪽 아래 방향으로 확장합니다.