Experimenter
Experimenter

Reputation: 167

Apply same color to same entity in for each loop in vb

Below code applies random color to all components in assembly irrespective of same or different name for each component. An assembly may have same named components packed together. I just want to apply same color when tempComp.DisplayName is same. I don't know how to check names during loop running or storing names somehow and compare. Any help will be appreciated.

        Dim i as integer = 0
    For Each tempComp As Assemblies.Component In myAsmInfo.AllComponents
        lw.WriteLine(tempComp.DisplayName & " | Color ID:" & i)
        ''' Select random color between 1 to 216
        i = CInt(Math.Ceiling(Rnd() * 216)) + 1

        Dim markId1 As NXOpen.Session.UndoMarkId = Nothing
        markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Edit Object Display")

        Dim displayModification1 As NXOpen.DisplayModification = Nothing
        displayModification1 = theSession.DisplayManager.NewDisplayModification()

        displayModification1.ApplyToAllFaces = True

        displayModification1.ApplyToOwningParts = False
        'lw.WriteLine("Color Before " & i)
        displayModification1.NewColor = i

        Dim objects1(0) As NXOpen.DisplayableObject

        objects1(0) = tempComp
        displayModification1.Apply(objects1)

        Dim nErrs1 As Integer = Nothing
        nErrs1 = theSession.UpdateManager.DoUpdate(markId1)

       ' lw.WriteLine("Color After " & i)
        displayModification1.Dispose()            

    Next 

Upvotes: 0

Views: 43

Answers (1)

JayV
JayV

Reputation: 3271

Given that you require storing tempComp.DisplayName and a numeric value along side that name, you need to use a Dictionary (Of String, Integer) to hold the values.

Before you start the For loop, add the line:

Dim coloursDictionary As New Dictionary(Of String, Integer)

And, inside the For loop, when deciding on the colour to be assigned use:

If coloursDictionary.ContainsKey(tempComp.DisplayName) Then
    i = coloursDictionary(tempComp.DisplayName)
Else
    i = CInt(Math.Ceiling(Rnd() * 216)) + 1
    coloursDictionary(tempComp.DisplayName) = i
End If

Upvotes: 1

Related Questions