碧血红天的HomePage

U3d杂谈 — 使用GraphView做工具04

前面内容,我们把节点归了类,然后限制了节点的执行方式。我们需要把自己实现的节点类型列出来,我们需要根据需要选择创建需要的节点。这里使用UXML和USS的方式来修改下我们Window的布局。

我们这里简单使用下UXML,我们把窗口分成左右布局,左边预留一个300宽度的区域用于显示ListView,右边的区域是GraphView视口。

<?xml version="1.0" encoding="utf-8"?>
<engine:UXML
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:engine="UnityEngine.UIElements"
    xmlns:editor="UnityEditor.UIElements"
    xsi:noNamespaceSchemaLocation="../UIElementsSchema/UIElements.xsd"
>
  <!--自定义内容开始-->
  <engine:VisualElement class="root" name="XXXXXX">
    <engine:VisualElement class="split left" name="listView">
      
    </engine:VisualElement>

    <engine:VisualElement class="split right" name="graphView">
      
    </engine:VisualElement>
  </engine:VisualElement>
  <!--自定义内容结束-->

</engine:UXML>

上面是UXML的内容,我们主要填充自定义内容区域即可。<engine:VisualElement>相当与Html中的<div>节点。

.root {
	width:100%;
	height:100%;
	display:flex;
	flex-direction: row;
}
.split {
  height: 100%;
  width: 50%;

  z-index: 1;
  top: 0;
  overflow-x: hidden;
  padding-top: 20px;
}

/* Control the left side */
.left {
  left: 0;
  width:300px;
  height:100%;
  background-color: #0b080e;
}

/* Control the right side */
.right {
  right: 0;
  width:100%;
  height:100%;
  background-color: red;
}

上面是uss的代码,跟CSS一样,定义样式。

现在我们修改我们的MyGraphWindow的类,通过UXML加载界面布局。

public static void OpenMyGraphView()
    {
        MyGraphWindow window = GetWindow<MyGraphWindow>("MyGraphWindow");


        VisualTreeAsset uiAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Editor/NodeMainWindowXML.uxml");
        VisualElement ui = uiAsset.CloneTree();

        //不使用自动创建的一个根节点,所以从第一个节点开始
        VisualElement rootUI = ui.ElementAt(0);
        var styleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/Editor/NodeMainWindowXML.uss");
        rootUI.styleSheets.Add(styleSheet);

        //通过Query查询节点,然后创建自己节点添加进去
        VisualElement gv = rootUI.Query<VisualElement>("graphView").First();
        graphView = new MyGraphView();
        gv.Add(graphView);

       //通过Query查询节点,然后创建自己节点添加ListView
        VisualElement lv = rootUI.Query<VisualElement>("listView").First();
        ListView nodeListMenu = new ListView();
        nodeListMenu.selectionType = SelectionType.Single;
        nodeListMenu.onItemChosen += (object e) => {
            NodeAttribute item = e as NodeAttribute;
            //Debug.Log(item.ClassName);
        };
        //选择ListView中的Item的时候会响应此回调
        nodeListMenu.onSelectionChanged += (List<object> e) => {
            NodeAttribute item = e[0] as NodeAttribute;
            //Debug.Log(item.ClassName);
        };
        VisualElementExtensions.StretchToParentSize(nodeListMenu);
        lv.Add(nodeListMenu);
        window.rootVisualElement.Add(rootUI);

        //反射添加节点在ListView中
        List<NodeAttribute> nodeInfos = new List<NodeAttribute>();
        foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
        {
            foreach (var type in assembly.GetTypes())
            {
                NodeAttribute info = type.GetCustomAttribute<NodeAttribute>();
                if (info != null)
                {
                    nodeInfos.Add(info);
                }
            }
        }

        //设置ListView创建的的代理函数
        Func<VisualElement> makeItem = () => {
            Label l = new Label();
            l.RegisterCallback<MouseDownEvent>((MouseDownEvent e) => {
                //通过双击创建节点
                if(e.clickCount == 2)
                {
                    NodeAttribute info = l.userData as NodeAttribute;
                    Debug.Log(info.ClassName);
                    var bNode = (Node)Activator.CreateInstance(info.ClassType);
                    graphView.AddElement(bNode);
                    //设置添加的节点从当前视口的左上角出现
                    Vector2 offsetPos = graphView.GetOffsetPos();
                    bNode.SetPosition(new Rect(offsetPos.x, offsetPos.y, bNode.localBound.width, bNode.localBound.height));
                }
            });

            return l;
        };

        //设置ListView刷新Item的代理函数
        Action<VisualElement, int> bindItem = (e, i) => { 
            (e as Label).text = nodeInfos[i].Alias;
            (e as Label).userData = nodeInfos[i];
        };
        nodeListMenu.makeItem = makeItem;
        nodeListMenu.bindItem = bindItem;
       //设置ListView的Item内容
        nodeListMenu.itemsSource = nodeInfos;
        nodeListMenu.itemHeight = 18;
    }

上面我们添加了如果通过UXML和USS创建窗口,然后通过代码添加ListView和GraphView挂到UXML创建的节点。我们实现通过双击来创建节点。默认创建的节点添加到GraphView会设置到(0,0)的位置,所以我们获取到contentViewContainer的偏移,这样每次创建的时候都能在视口的左上角。

为了通过反射自动认识需要添加的节点进入ListView中,我们添加一个自定义的Attribute.

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[AttributeUsage(AttributeTargets.Class)]
public class NodeAttribute : Attribute
{
    private string className;
    private string alias;
    private Type classType;
    public NodeAttribute(string name,string a, Type t)
    {
        className = name;
        alias = a;
        classType = t;
    }

    public string ClassName
    {
        get
        {
            return className;
        }
    }

    public string Alias
    {
        get
        {
            return alias;
        }
    }

    public Type ClassType
    {
        get
        {
            return classType;
        }
    }
}

我们自定义属性设置为修饰类,然后添加3个属性,一个是类的名字,显示在ListView中的别名,还有类的Type。现在我们在我们添加的3个节点类型上添加上我们的属性:

[NodeAttribute("AddIntNode","Int加", typeof(AddIntNode))]
public class AddIntNode : ProcessBaseNode
//省略下面代码
[NodeAttribute("LogNode", "日志输出",typeof(LogNode))]
public class LogNode : ProcessBaseNode
//省略下面代码

好了,现在我们打开窗口,能够通过反射自动识别我们的节点了。

最后展示的效果如下。接下来我们说说如何保存我们的内容(序列化),不然关闭此窗口就导致我们编辑的节点消失了。

36 评论

  1. Hello there! This is my 1st comment here so I just wanted to give a quick shout out and tell you I really enjoy reading your blog posts. Can you recommend any other blogs/websites/forums that deal with the same topics? Thanks a ton!

  2. In a pinch ar r chems in travel size mouthwash whitening rinse bottles have worked well lasix more drug uses

  3. eHealthMe is studying from 32, 996 Zithromax users for its effectiveness, alternative drugs and more reddit priligy Tubes were incubated in a shaking 37 C incubator, and absorbance measurements at 600 nm were taken every hour up to 7 h, and once at 24 h, using a Spectronic 20D spectrophotometer Thermo Scientific, Waltham, MA, USA

  4. Recent studies have reported several promising biomarkers that are currently being validated through clinical trials buy generic stromectol

  5. Very interesting info !Perfect just what I was searching for! “It’s not the having, its the getting.” by Elizabeth Taylor.

  6. Regards for this post, I am a big fan of this website would like to go on updated.

  7. Great post. I used to be checking constantly this blog and I am impressed! Very helpful information specially the remaining part 🙂 I deal with such information much. I used to be seeking this certain info for a long time. Thank you and good luck.

  8. Susanne Kilpinen tamoxifen hair loss Chemist direct light and antiestrogenic effects

  9. I like what you guys are up too. Such intelligent work and reporting! Carry on the superb works guys I have incorporated you guys to my blogroll. I think it’ll improve the value of my web site 🙂

  10. This is really interesting, You are a very skilled blogger. I’ve joined your rss feed and look forward to seeking more of your great post. Also, I have shared your site in my social networks!

  11. I have been reading out a few of your stories and it’s pretty clever stuff. I will definitely bookmark your blog.

  12. Hi, Neat post. There’s an issue along with your web site in web explorer, might check this?K IE still is the marketplace chief and a good component of other folks will pass over your wonderful writing because of this problem.

  13. Some truly rattling work on behalf of the owner of this internet site, absolutely great articles.

  14. Thanx for the effort, keep up the good work Great work, I am going to start a small Blog Engine course work using your site I hope you enjoy blogging with the popular BlogEngine.net.Thethoughts you express are really awesome. Hope you will right some more posts.

  15. This website online is known as a stroll-by for all of the information you wished about this and didn’t know who to ask. Glimpse right here, and you’ll positively uncover it.

  16. Hello my family member! I want to say that this article is amazing, great written and include almost all significant infos. I would like to peer more posts like this .

  17. I think other website proprietors should take this site as an model, very clean and wonderful user genial style and design, as well as the content. You’re an expert in this topic!

  18. I’ve learn some excellent stuff here. Definitely worth bookmarking for revisiting. I surprise how so much effort you set to create such a great informative site.

  19. Hey there just wanted to give you a brief heads up and let you know a few of the images aren’t loading correctly. I’m not sure why but I think its a linking issue. I’ve tried it in two different web browsers and both show the same outcome.

  20. I’m very happy to read this. This is the type of manual that needs to be given and not the random misinformation that’s at the other blogs. Appreciate your sharing this greatest doc.

  21. of course like your web-site however you need to take a look at the spelling on several of your posts. Several of them are rife with spelling problems and I find it very troublesome to inform the reality on the other hand I will certainly come again again.

  22. Hello.This article was really fascinating, particularly since I was browsing for thoughts on this subject last Tuesday.

  23. My husband and i were comfortable John could conclude his researching through the ideas he discovered from your own web pages. It’s not at all simplistic to simply always be giving out key points that many people today have been making money from. So we acknowledge we have got the writer to appreciate for that. Most of the explanations you’ve made, the easy blog navigation, the friendships you will help to instill – it’s got everything excellent, and it is leading our son in addition to the family believe that this article is awesome, and that is especially serious. Thank you for all the pieces!

  24. I know this if off topic but I’m looking into starting my own blog and was curious what all is needed to get set up? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web savvy so I’m not 100 certain. Any recommendations or advice would be greatly appreciated. Cheers

  25. I visited a lot of website but I conceive this one has got something extra in it in it

  26. It’s perfect time to make some plans for the future and it is time to be happy. I have read this post and if I could I desire to suggest you some interesting things or advice. Maybe you could write next articles referring to this article. I want to read more things about it!

  27. Along with every thing that appears to be building within this particular subject matter, many of your opinions tend to be relatively radical. Having said that, I appologize, because I do not subscribe to your whole idea, all be it refreshing none the less. It would seem to everybody that your remarks are actually not totally rationalized and in simple fact you are generally your self not even completely confident of the point. In any case I did enjoy reading it.

  28. Simultaneously women received 2 online finasteride prescription However, the molecular mechanism responsible has not been well established

  29. buy stromectol for humans online The indications were as follows unfavorable correlation between tumor size and breast size in 53 patients, 10 patients with multifocal or multicentric tumors and breast cancer recurrence after breast conserving surgery in six patients

  30. Hepatic toxicity has not been commonly observed clomiphene moa

  31. A Rebuttal of the Beta Carotene Vitamin E Study letter 132, p z pack price

  32. cialis order online As mentioned before, cervical cancers were observed when both genotypes were treated with E2 for 8 months 2 of 15 K14E7 ERО± f f 8mE2 Tam mice and one of four CMVCreER K14E7 ERО± f f 8mE2 Tam mice

  33. com 20 E2 AD 90 20Kur 20Nopirkt 20Viagra 20Tabletes 20 20Cara 20Minum 20Obat 20Viagra 20Usa cara minum obat viagra usa Timberlake made up for that minor loss with added triumphs in the categories of Best Direction for Гў Suit TieГў and Best Editing for Гў Mirrors nolvadex dosage for epistane

  34. Practice guidelines convey only limited insight into the utility of complex combination therapy side effects of azithromycin

发表评论