I want to see if my prim has a collection with a specific name or not.
I tried on my own, but then asked nvidia’s ai code generator for help and it suggested this:
Write a python function that takes a prim and a collection name and determines if that collection already exists on the prim.
from pxr import Usd, UsdGeom, Sdf
def collection_exists_on_prim(prim, collection_name):
"""
Check if a collection with the given name already exists on a prim.
Args:
prim (Usd.Prim): The prim to check.
collection_name (str): The name of the collection to look for.
Returns:
bool: True if the collection exists on the prim, False otherwise.
"""
if prim.HasAPI(Usd.CollectionAPI):
collection_api = Usd.CollectionAPI.Get(prim, collection_name)
return collection_api is not None
return False
# Example usage:
stage = Usd.Stage.CreateInMemory()
prim = stage.DefinePrim("/MyPrim", "Xform")
collection_name = "MyCollection"
Usd.CollectionAPI.Apply(prim, collection_name)
print(collection_exists_on_prim(prim, collection_name)) # Output: True
Which okay… addresses half the issue. But then I can:
print(collection_exists_on_prim(prim, "i_dont_exist"))
which also gives me True.
So then I could do something like:
collection_api_names = [x.GetName() for x in Usd.CollectionAPI.GetAllCollections(prim)]
# then test
collection_name in collection_api_names
and that will work. But I feel kind of icky.