- Home /
Question by
unity_28main28 · Feb 27, 2018 at 02:18 AM ·
collisioncollider2d-platformercollision detectioncollider2d
I am trying to create all elements in the scene from one script at run time. How do I detect collisions between the enemy and the coin without having to create another script for each item?
using UnityEngine;
using System.Collections;
public class algorithmTest : MonoBehaviour {
public Sprite coin;
public Sprite enemy;
void Start() {
GameObject go4 = new GameObject("Coin");
SpriteRenderer rendererCoin4 = go4.AddComponent<SpriteRenderer>();
rendererCoin4.sprite = coin;
go4.GetComponent<SpriteRenderer>().color = new Color(1, 0.92f, 0.016f, 1);
go4.AddComponent<PolygonCollider2D>();
go4.transform.localScale = new Vector3(1,1,1);
GameObject go5 = new GameObject("Enemy");
SpriteRenderer rendererEnemy5 = go5.AddComponent<SpriteRenderer>();
rendererEnemy5.sprite = enemy;
go5.AddComponent<PolygonCollider2D>();
Rigidbody2D gameObjectsRigidBody = go5.AddComponent<Rigidbody2D>();
gameObjectsRigidBody.mass = 1000;
gameObjectsRigidBody.constraints = RigidbodyConstraints2D.FreezeRotation;
go5.transform.localScale = new Vector3(.75f,.75f,1);
go5.transform.localRotation = Quaternion.Euler(0,180,0);
GameObject coinGroundPrefab = go4;
GameObject enemyPrefab = go5;
coinGroundPrefab.transform.position = new Vector3(448.26f,-4,0);
Instantiate (coinGroundPrefab);
enemyPrefab.transform.position = new Vector3(575.135f,.2534971f,0);
Instantiate (enemyPrefab);
}
}
Comment
Your answer
Follow this Question
Related Questions
Objects falling through EdgeCollider2D on the ground 0 Answers
How to set collision for an object with specific collider size? 3 Answers
Collision detection problem 0 Answers
Player Gets Stuck On TilemapCollider2D 0 Answers
Detect polygon? 0 Answers