SOLVED Beginner:How to assign A-material to B-cube by python?

(😁 Thanks to all the good people who kindly answer questions to a green hand like me in recent days ,i have certainly made a huge pregress due to you zealous guys in such a super forum)

Well,i meet the problem to assign a material to another object in my project,i reviewed history post but not so solvable,let me take an easy example of A material and B cube,how to assign A to B?

Below is example pic
mat assign.png

import c4d

def main():
   A = c4d.BaseObject(c4d.Ocube)
#lost on how to make assignment




Thanks !
ilad

Hi Ilad, thanks for reaching out us.

With regard to your request, I warmly recommend to have a look at Materials and Shaders Overview where the basic of Cinema 4D materials and shading handling are discussed. Consider that even if the documentation refers to C++ the described concepts can be applied to Python as well.

Briefly the solution to your request is:

def main():
    # get first object
    cubeA = doc.GetActiveObject()
    if cubeA is None: 
       return
   
    # get second object
    cubeB = op.GetNext()
    if cubeB is None:
        cubeB = op.GetPred()
    
    #get first material
    matA = doc.GetActiveMaterial()
    if matA is None: 
        return
    
    # get second material
    matB = matA.GetNext()
    if matB is None:
        matB = matA.GetPred()
    
    # create the texture tags for A and B
    ttagA = c4d.TextureTag()
    ttagB = c4d.TextureTag()
    
    # assign the swapped materials to the texture tags
    ttagA.SetMaterial(matB)
    ttagB.SetMaterial(matA)
    
    # insert the tags to the corresponding objects
    cubeA.InsertTag(ttagA)
    cubeB.InsertTag(ttagB)
    
    # queue an event
    c4d.EventAdd()

Last but not least, it's recommended for future threads to use the appropriate category and mark it as "Ask as a question" upon creation.

Best, Riccardo

@r_gigante Thanks!Greate help for me! I got it!😁