Unity common game basic functions

Generate a new Object

public GameObject objectPrefab;

GameObject newObject = Instantiate(objectPrefab) as GameObject;			//1
GameObject newObject = (GameObject)Instantiate(objectPrefab);			//2
Transform newObject = Instantiate(myPrefab) as Transform;				//3
Transform newObject = (Instantiate(myPrefab) as GameObject).transform;	//4
Transform newObject = (Instantiate(myPrefab) as GameObject).GetComponent<Transform>();	//5

The more recommended ObjectPool

public GameObject objectPrefab;
public Transform inUseParent;
public List<Transform> objectInPool;
public List<Transform> objectInUse;

public Transform GetNewObject()
{
    
    
	Transform newObj = null;
	if(objectInPool.Count > 0)
	{
    
    
		newObj = objectInPool[0];
		SetObjStatus(newObj, true);
	}
	else
	{
    
    
		newObj = (Instantiate(objectPrefab) as GameObject).transform;
        objectTransform.SetParent(inUseParent, false);
        SetObjStatus(newObj, true);
	}
	return newObj;
}

public void SetObjStatus(Transform obj, bool SetToInUse)
{
    
    
	if(obj != null)
	{
    
    
		obj.gameObject.SetActive(SetToInUse);
		if(SetToInUse)
		{
    
    
			if(objectInPool.Contains(obj))
			{
    
    
				objectInPool.Remove(obj);
			}
			if(!objectInUse.Contains(obj))
			{
    
    
				objectInUse.Add(obj);
			}
		}
		else
		{
    
    
			if(!objectInPool.Contains(obj))
			{
    
    
				objectInPool.Add(obj);
			}
			if(objectInUse.Contains(obj))
			{
    
    
				objectInUse.Remove(obj);
			}
		}
	}
}

Collider

  1. First of all, there must be Collider on all related GameObjects, and IsTrigger is not checked .
  2. Any one of the GameObjects that trigger Collider must have RigiBody, and its UseGravity must be checked, and IsKinematic cannot be checked.
  3. If you don't want it to be affected by gravity, please modify other parameters.
private void OnCollisionEnter(Collision col)
{
    
    
	Debug.Log("Col Enter");
	
}

Guess you like

Origin blog.csdn.net/MikeW138/article/details/103557518