Is it possible to create a gameobject with a collider upon instantiation? I want to Instantiate a gameobject that only has a flat sphere Collider but I don’t want create it as a prefab and then instantiate it because I want to create the scale upon instantiation. I’m unsure how to instantiate a gameobject and then add a flat sphere collider to it. Would you create the gameobject as a variable and then use it?
clunk47
2
using UnityEngine;
using System.Collections;
public class CreateNewGO : MonoBehaviour
{
GameObject go;
GameObject meshObject;
void Awake()
{
go = GameObject.CreatePrimitive(PrimitiveType.Sphere);
go.transform.position = transform.position + (transform.forward * 5)+(-transform.up);
Destroy (go.GetComponent<SphereCollider>());
//Change mesh of go. Will load object from Resources/Prefabs/Put name of your prefab here.
meshObject = (GameObject)Resources.Load ("Prefabs/NameOfYourPrefab");
go.GetComponent<MeshFilter>().mesh = (Mesh)Instantiate(meshObject.GetComponent<MeshFilter>().mesh);
go.transform.localScale = new Vector3(3, 3, 3);
go.AddComponent<MeshCollider>();
//Test collider with rigidbody
GameObject test = GameObject.CreatePrimitive(PrimitiveType.Sphere);
test.transform.localScale = new Vector3(.3f, .3f, .3f);
test.transform.position = transform.position + Vector3.forward * 5;
test.AddComponent<ConstantForce>().force = Vector3.right;
}
}