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?
1 Answer
1using 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;
}
}
How do you change what the mesh collider's mesh in C#?I know you can change what it is directly on the gameobject via the inspector but I don't know how to change it in a C# script. I only want the flat sphere collider. No mesh renderer or filter. I really don't want to do that by creating a primtiveType.Sphere and then destroying it's components.
– OchreousEdited answer to include changing mesh at runtime.
– clunk47In order to get the kind of collider I'm looking for am I going to need to create a prefab? I was trying to avoid that.
– OchreousWell you need to have a mesh to go off of.... Otherwise you need to write your vertices at runtime... I think I don't fully understand exactly what you're trying to do..
– clunk47I'm trying to make a collider that's in the shape of a flat sphere with no mesh showing. I think I might only need to get rid of the mesh renderer to achieve that.
– Ochreous