void Awake() { lightMesh = new Mesh(); lightMesh.name = string.Format("Light Mesh ({0})", name); lightMesh.MarkDynamic(); meshFilter = GetComponent<MeshFilter>(); meshFilter.mesh = lightMesh; meshRenderer = GetComponent<MeshRenderer>(); meshRenderer.sharedMaterial = lightMaterial; var container = transform.Find("LightMesh"); if (!container) { container = new GameObject("LightMesh").transform; container.SetParent(transform, true); container.localPosition = Vector3.zero; container.gameObject.layer = gameObject.layer; } lightMeshCollider = container.GetComponent<PolygonCollider2D>(); if (lightMeshCollider == null) { lightMeshCollider = container.gameObject.AddComponent<PolygonCollider2D>(); } lightMeshCollider.isTrigger = true; vertices = new List<Vertex>(); UpdateLightFX(); }
static Transform GetOrCreateChild(Transform root, string name) { var child = root.Find(name); if (!child) { child = new GameObject(name).transform; child.SetParent(root, false); } return child; }
Transform LinkFolder(NodeInstance node) { var linksFolder = node.transform.Find("Links"); if (linksFolder == null) { linksFolder = new GameObject("Links").transform; linksFolder.SetParent(node.transform); linksFolder.transform.Reset(); } return linksFolder; }
Transform GetNested(string name) { if (nestedViewContainers.ContainsKey(name)) { return nestedViewContainers[name]; } var nestedView = new GameObject(name).transform; nestedView.SetParent(viewContainer, false); nestedViewContainers[name] = nestedView; return nestedView; }
// BIG TODO: change the hierarchy to a messaging system void Start() { // TODO: make this read from a file instead of hardcoded ofc lol foodWeb = new RungeEcosystem(); foodWeb.AddSpecies("grass", -0.03f, 1.0f, 0f); foodWeb.AddSpecies("oak tree", -0.03f, 0.8f, 10f); foodWeb.AddSpecies("berries", -0.03f, 0.6f, 10f); foodWeb.AddSpecies("rabbit", -0.01f, -0.1f, 0f); foodWeb.AddSpecies("caterpillar", -0.01f, -0.2f, 10f); foodWeb.AddSpecies("squirrel", -0.01f, -0.2f, 10f); foodWeb.AddSpecies("fox", -0.01f, -0.2f, 0f); foodWeb.AddInteraction("rabbit", "grass", 0.05f, 0.8f); foodWeb.AddInteraction("rabbit", "berries", 0.02f, 0.8f); foodWeb.AddInteraction("squirrel", "berries", 0.02f, 0.8f); foodWeb.AddInteraction("squirrel", "oak tree", 0.04f, 0.8f); foodWeb.AddInteraction("caterpillar", "oak tree", 0.04f, 0.8f); foodWeb.AddInteraction("fox", "berries", 0.02f, 0.5f); foodWeb.AddInteraction("fox", "squirrel", 0.02f, 0.6f); foodWeb.AddInteraction("fox", "rabbit", 0.05f, 0.6f); foodWeb.AddInteraction("fox", "caterpillar", 0.01f, 0.5f); // TODO: add humans hunting as the interesting bit of this ecosystem Transform iconTransform = new GameObject("Icon Manager").transform; // for organisation iconTransform.SetParent(transform); iconWeb = new IconManager(iconTransform, transferPrefab, interactionPrefab); iconWeb.AddSpecies("grass", 'p', 0f, 0f, 100f, 1f, iconPrefab, pictures[0], Color.green); iconWeb.AddSpecies("oak tree", 'p', 0f, 10f, 100f, 1f, iconPrefab, pictures[1], Color.black); iconWeb.AddSpecies("berries", 'p', 0f, 10f, 100f, 1f, iconPrefab, pictures[2], Color.magenta); iconWeb.AddSpecies("rabbit", 'h', 1f, 0f, 100f, 1f, iconPrefab, pictures[3], Color.grey); iconWeb.AddSpecies("caterpillar", 'h', 0.03f, 10f, 100f, 1f, iconPrefab, pictures[4], Color.yellow); iconWeb.AddSpecies("squirrel", 'h', 0.5f, 10f, 100f, 1f, iconPrefab, pictures[5], Color.white); iconWeb.AddSpecies("fox", 'o', 5f, 0f, 100f, 1f, iconPrefab, pictures[6], Color.red); speciesNames = new List<string>(); speciesNames.Add("grass"); speciesNames.Add("oak tree"); speciesNames.Add("berries"); speciesNames.Add("rabbit"); speciesNames.Add("caterpillar"); speciesNames.Add("squirrel"); speciesNames.Add("fox"); foreach (string species in speciesNames) SetIconInteractionSprings(species); CreateGraph(); InvokeRepeating("UpdateIconPopulations", 0.7f, 2f); screenWidth = 2f * Camera.main.orthographicSize * Screen.width / Screen.height; screenHeight = screenWidth / Screen.width * Screen.height; gui = transform.Find("GUI").GetComponent<GUI>(); gui.Init(screenWidth, screenHeight); }
void CreateSpawner(int index) { Transform rotater = new GameObject("Rotater").transform; rotater.SetParent(transform, false); rotater.localRotation = Quaternion.Euler(0f, index * (360f / numberOfSpawners), 0f); StuffSpawner spawner = Instantiate<StuffSpawner>(spawnerPrefab); spawner.transform.SetParent(rotater, false); spawner.transform.localPosition = new Vector3(0f, 0f, radius); spawner.transform.localRotation = Quaternion.Euler(tiltAngle, 0f, 0f); spawner.stuffMaterial = stuffMaterials[index % stuffMaterials.Length]; }
static Transform GetNested(string name, Transform viewContainer, IDictionary<string, Transform> nestedViewContainer) { if (nestedViewContainer.ContainsKey(name)) { return nestedViewContainer[name]; } var nestedView = new GameObject(name).transform; nestedView.SetParent(viewContainer, false); nestedViewContainer[name] = nestedView; return nestedView; }
public static void CreateJoystick() { GameObject joystick = new GameObject("Joystick", typeof(Image), typeof(EasyJoystick) , typeof(CanvasGroup)); joystick.GetComponent<Image>().sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>(kKnobPath); joystick.GetComponent<RectTransform> ().sizeDelta = Vector2.one * 150; joystick.layer = LayerMask.NameToLayer(kUILayerName); RectTransform stick = new GameObject("Stick", typeof(Image)).GetComponent<RectTransform>(); stick.gameObject.GetComponent<Image>().sprite = AssetDatabase.GetBuiltinExtraResource<Sprite>(kKnobPath); stick.sizeDelta = Vector2.one * 60; stick.SetParent (joystick.transform, false); stick.gameObject.layer = LayerMask.NameToLayer(kUILayerName); joystick.GetComponent<EasyJoystick> ().stick = stick; SetCanvas (joystick.transform); Debug.Log("Joystick has been created"); Selection.activeGameObject = joystick; }
/// <summary> /// Spawn the GameObject of the blocks prefab /// </summary> /// <param name="parent">Parent of GameObject</param> /// <param name="pos">Local position to spawn at</param> public override void InstantiateBlock(Transform parent, Vector3 pos, int x, int y, int z, Block[,,] blocks) { //Create parent gameobject to store position of block Transform posOffset = new GameObject(GetName()).transform; posOffset.SetParent(parent); posOffset.localPosition = pos + new Vector3(0f, -0.5f, 0f); //Instantiate block gameObject = Object.Instantiate(GetPrefab()) as GameObject; transform = gameObject.transform; //Set parent transform.SetParent(posOffset); transform.localPosition = Vector3.zero; //Create spawnable controller SpawnableController controller = gameObject.AddComponent<SpawnableController>(); controller.SetBlock(this); Spawn(); }
// Use this for initialization void Start () { m_animator = GetComponent<Animator>(); GameObject baggage_obj = null; if (m_Baggages.Length > 0) { var i = Random.Range(0, m_Baggages.Length + 1); if (i < m_Baggages.Length) { baggage_obj = GameObject.Instantiate(m_Baggages[i]); var baggage = baggage_obj.transform; var seat = transform.Find(m_BaggageOriginName); var joint = new GameObject("Joint").transform; joint.localPosition = new Vector3( m_BaggageOrigin.x / seat.localScale.x, m_BaggageOrigin.z / seat.localScale.z, m_BaggageOrigin.y / seat.localScale.y); joint.localScale = new Vector3( 1.0f / seat.localScale.x, 1.0f / seat.localScale.z, 1.0f / seat.localScale.y); joint.SetParent(seat, false); baggage.SetParent(joint, false); } } }
public static GameObject BuildActionProjectile( Game1 game, GameObject parent, ActionInfo actInfo, Vector2 position, Vector2 velocity, int lifetime, List<Shape> boundingBoxes) { GameObject entity = new GameObject(game); entity.SetParent(parent); Transform2DComponent transformComponent = new Transform2DComponent( entity, position, 0.0f, Vector2.One); BoundingBoxComponent bbComponent = new BoundingBoxComponent(entity, boundingBoxes, true); CurrentActionComponent caComponent = new CurrentActionComponent( entity, new ActionComponent(DirectionalAction.Left, SecondaryAction.Stand, PrimaryAction.None), new Dictionary<ActionDefinition, ActionInfo>()); LifetimeComponent lifetimeComponent = new LifetimeComponent(entity, lifetime); IsActionComponent isActionComponent = new IsActionComponent(entity, actInfo); MotionPropertiesComponent motionComponent = new MotionPropertiesComponent(entity, 1.0f); motionComponent.SetVelocity(velocity); entity.AddComponent(transformComponent); entity.AddComponent(bbComponent); entity.AddComponent(caComponent); entity.AddComponent(motionComponent); entity.AddComponent(lifetimeComponent); entity.AddComponent(isActionComponent); return entity; }
/// <summary> /// Add a toggle to this Screen Effects subcategory. /// </summary> /// <param name="text">Label text</param> /// <param name="setter">Method to be called when the toggle changes value</param> /// <param name="initialValue">Initial state of the toggle</param> /// <returns>Instance of the ToggleSet</returns> public SceneEffectsToggleSet AddToggleSet(string text, Action <bool> setter, bool initialValue) { var containingElement = new GameObject().AddComponent <RectTransform>(); containingElement.name = text; containingElement.SetParent(Content.transform, false); KoikatuAPI.Instance.StartCoroutine(SetPosDelayed(containingElement.transform, GetCurrentOffset())); var label = Object.Instantiate(_labelSource).GetComponent <TextMeshProUGUI>(); label.transform.SetParent(containingElement.transform, false); label.transform.localPosition = new Vector3(4f, 0f, 0f); var toggle = Object.Instantiate(_toggleSource).GetComponent <Toggle>(); toggle.transform.SetParent(containingElement.transform, false); toggle.transform.localPosition = new Vector3(160f, 0f, 0f); var toggleSet = new SceneEffectsToggleSet(label, toggle, text, setter, initialValue); Toggles.Add(toggleSet); return(toggleSet); }
public void SetUI(List <SeatEntity> seatList) { for (int i = 0; i < seatList.Count; i++) { if (seatList[i].PlayerId == 0) { continue; } if (seatList[i] == RoomGuPaiJiuProxy.Instance.PlayerSeat) { string scoreText = string.Format(seatList[i].eamings >= 0 ? "+{0}" : "{1}", seatList[i].eamings, seatList[i].eamings); currPlayerScore.color = seatList[i].eamings >= 0 ? Color.white : Color.red; currPlayerScore.text = scoreText; } else { GameObject go = Instantiate(m_smallResultObj); go.SetActive(true); go.SetParent(m_smallResultTran); go.GetComponent <UIItemGuPaiJiuSmallResult>().SetUI(seatList[i]); } } StartCoroutine(SetBtn()); }
// Will create proxy if does not exist private ProxyTransform GetProxyTransform(int charIndex) { if (proxyTransformDict == null) { proxyTransformDict = new Dictionary <int, ProxyTransform>(CharacterCount); proxyTransformList = new List <ProxyTransform>(CharacterCount); } ProxyTransform proxy; if (!proxyTransformDict.TryGetValue(charIndex, out proxy)) { Transform t = new GameObject(charIndex.ToString()).transform; t.SetParent(proxyTransformParent); proxy = charIndex >= CharacterCount ? new ProxyTransform(t, proxyTransformParent, charIndex) : new ProxyTransform(t, proxyTransformParent, Text.textInfo.characterInfo[charIndex]); proxyTransformDict.Add(charIndex, proxy); proxyTransformList.Add(proxy); } return(proxy); }
protected override void DidActivate(bool firstActivation, ActivationType type) { if (firstActivation && type == ActivationType.AddedToHierarchy) { rectTransform.anchorMin = new Vector2(0.5f, 0f); rectTransform.anchorMax = new Vector2(0.5f, 1f); rectTransform.sizeDelta = new Vector2(74f, 0f); rectTransform.pivot = new Vector2(0.4f, 0.5f); _pageUpButton = Instantiate(Resources.FindObjectsOfTypeAll <Button>().First(x => (x.name == "PageUpButton")), rectTransform, false); (_pageUpButton.transform as RectTransform).anchorMin = new Vector2(0.5f, 1f); (_pageUpButton.transform as RectTransform).anchorMax = new Vector2(0.5f, 1f); (_pageUpButton.transform as RectTransform).anchoredPosition = new Vector2(0f, -14f); (_pageUpButton.transform as RectTransform).sizeDelta = new Vector2(40f, 10f); _pageUpButton.interactable = true; _pageUpButton.onClick.AddListener(delegate() { pageUpPressed?.Invoke(); }); _pageUpButton.interactable = false; _pageDownButton = Instantiate(Resources.FindObjectsOfTypeAll <Button>().First(x => (x.name == "PageDownButton")), rectTransform, false); (_pageDownButton.transform as RectTransform).anchorMin = new Vector2(0.5f, 0f); (_pageDownButton.transform as RectTransform).anchorMax = new Vector2(0.5f, 0f); (_pageDownButton.transform as RectTransform).anchoredPosition = new Vector2(0f, 8f); (_pageDownButton.transform as RectTransform).sizeDelta = new Vector2(40f, 10f); _pageDownButton.interactable = true; _pageDownButton.onClick.AddListener(delegate() { pageDownPressed?.Invoke(); }); _sortByButton = BeatSaberUI.CreateUIButton(rectTransform, "CreditsButton", new Vector2(15f, 36.25f), new Vector2(30f, 6f), () => { SelectTopButtons(TopButtonsState.SortBy); }, "Sort by"); _sortByButton.SetButtonTextSize(3f); _topButton = BeatSaberUI.CreateUIButton(rectTransform, "CreditsButton", new Vector2(-20f, 36.25f), new Vector2(20f, 6f), () => { sortByTop?.Invoke(); SelectTopButtons(TopButtonsState.Select); }, "Downloads"); _topButton.SetButtonTextSize(3f); _topButton.ToggleWordWrapping(false); _topButton.gameObject.SetActive(false); _newButton = BeatSaberUI.CreateUIButton(rectTransform, "CreditsButton", new Vector2(0f, 36.25f), new Vector2(20f, 6f), () => { sortByNew?.Invoke(); SelectTopButtons(TopButtonsState.Select); }, "Newest"); _newButton.SetButtonTextSize(3f); _newButton.ToggleWordWrapping(false); _newButton.gameObject.SetActive(false); _starButton = BeatSaberUI.CreateUIButton(rectTransform, "CreditsButton", new Vector2(20f, 36.25f), new Vector2(20f, 6f), () => { sortByPlays?.Invoke(); SelectTopButtons(TopButtonsState.Select); }, "Plays"); _starButton.SetButtonTextSize(3f); _starButton.ToggleWordWrapping(false); _starButton.gameObject.SetActive(false); _searchButton = BeatSaberUI.CreateUIButton(rectTransform, "CreditsButton", new Vector2(-15, 36.25f), new Vector2(30f, 6f), () => { searchButtonPressed?.Invoke(); SelectTopButtons(TopButtonsState.Search); }, "Search"); _searchButton.SetButtonTextSize(3f); _loadingIndicator = BeatSaberUI.CreateLoadingSpinner(rectTransform); (_loadingIndicator.transform as RectTransform).anchorMin = new Vector2(0.5f, 0.5f); (_loadingIndicator.transform as RectTransform).anchorMax = new Vector2(0.5f, 0.5f); (_loadingIndicator.transform as RectTransform).anchoredPosition = new Vector2(0f, 0f); _loadingIndicator.SetActive(true); _songListTableCellInstance = Resources.FindObjectsOfTypeAll <LevelListTableCell>().First(x => (x.name == "LevelListTableCell")); RectTransform container = new GameObject("CustomListContainer", typeof(RectTransform)).transform as RectTransform; container.SetParent(rectTransform, false); container.sizeDelta = new Vector2(60f, 0f); _songsTableView = new GameObject("CustomTableView", typeof(RectTransform)).AddComponent <TableView>(); _songsTableView.gameObject.AddComponent <RectMask2D>(); _songsTableView.transform.SetParent(container, false); _songsTableView.SetPrivateField("_isInitialized", false); _songsTableView.SetPrivateField("_preallocatedCells", new TableView.CellsGroup[0]); _songsTableView.Init(); (_songsTableView.transform as RectTransform).anchorMin = new Vector2(0f, 0f); (_songsTableView.transform as RectTransform).anchorMax = new Vector2(1f, 1f); (_songsTableView.transform as RectTransform).sizeDelta = new Vector2(0f, 60f); (_songsTableView.transform as RectTransform).anchoredPosition = new Vector2(0f, -3f); _songsTableView.dataSource = this; _songsTableView.didSelectCellWithIdxEvent += _songsTableView_DidSelectRowEvent; } else { _songsTableView.ReloadData(); } }
protected override void DidActivate(bool firstActivation, ActivationType type) { if (firstActivation && type == ActivationType.AddedToHierarchy) { SongDownloader.Instance.songDownloaded -= SongDownloaded; SongDownloader.Instance.songDownloaded += SongDownloaded; _songListTableCellInstance = Resources.FindObjectsOfTypeAll <LevelListTableCell>().First(x => (x.name == "LevelListTableCell")); RectTransform viewControllersContainer = FindObjectsOfType <RectTransform>().First(x => x.name == "ViewControllers"); var headerPanelRectTransform = Instantiate(viewControllersContainer.GetComponentsInChildren <RectTransform>(true).First(x => x.name == "HeaderPanel" && x.parent.name == "PlayerSettingsViewController"), rectTransform); headerPanelRectTransform.gameObject.SetActive(true); _titleText = headerPanelRectTransform.GetComponentInChildren <TextMeshProUGUI>(); _titleText.text = "DOWNLOAD QUEUE"; _pageUpButton = Instantiate(Resources.FindObjectsOfTypeAll <Button>().Last(x => (x.name == "PageUpButton")), rectTransform, false); (_pageUpButton.transform as RectTransform).anchorMin = new Vector2(0.5f, 1f); (_pageUpButton.transform as RectTransform).anchorMax = new Vector2(0.5f, 1f); (_pageUpButton.transform as RectTransform).anchoredPosition = new Vector2(0f, -18f); (_pageUpButton.transform as RectTransform).sizeDelta = new Vector2(40f, 10f); _pageUpButton.interactable = true; _pageUpButton.onClick.AddListener(delegate() { _queuedSongsTableView.PageScrollUp(); }); _pageDownButton = Instantiate(Resources.FindObjectsOfTypeAll <Button>().First(x => (x.name == "PageDownButton")), rectTransform, false); (_pageDownButton.transform as RectTransform).anchorMin = new Vector2(0.5f, 0f); (_pageDownButton.transform as RectTransform).anchorMax = new Vector2(0.5f, 0f); (_pageDownButton.transform as RectTransform).anchoredPosition = new Vector2(0f, 9f); (_pageDownButton.transform as RectTransform).sizeDelta = new Vector2(40f, 10f); _pageDownButton.interactable = true; _pageDownButton.onClick.AddListener(delegate() { _queuedSongsTableView.PageScrollDown(); }); RectTransform container = new GameObject("CustomListContainer", typeof(RectTransform)).transform as RectTransform; container.SetParent(rectTransform, false); container.anchorMin = new Vector2(0.2f, 0.5f); container.anchorMax = new Vector2(0.8f, 0.5f); container.sizeDelta = new Vector2(0f, 0f); container.anchoredPosition = new Vector2(0f, -4f); _queuedSongsTableView = new GameObject("CustomTableView", typeof(RectTransform)).AddComponent <TableView>(); _queuedSongsTableView.gameObject.AddComponent <RectMask2D>(); _queuedSongsTableView.transform.SetParent(container, false); _queuedSongsTableView.SetPrivateField("_isInitialized", false); _queuedSongsTableView.SetPrivateField("_preallocatedCells", new TableView.CellsGroup[0]); _queuedSongsTableView.Init(); (_queuedSongsTableView.transform as RectTransform).anchorMin = new Vector2(0f, 0f); (_queuedSongsTableView.transform as RectTransform).anchorMax = new Vector2(1f, 1f); (_queuedSongsTableView.transform as RectTransform).sizeDelta = new Vector2(0f, 54f); (_queuedSongsTableView.transform as RectTransform).anchoredPosition = new Vector2(0f, 0f); ReflectionUtil.SetPrivateField(_queuedSongsTableView, "_pageUpButton", _pageUpButton); ReflectionUtil.SetPrivateField(_queuedSongsTableView, "_pageDownButton", _pageDownButton); _queuedSongsTableView.selectionType = TableViewSelectionType.None; _queuedSongsTableView.dataSource = this; _abortButton = BeatSaberUI.CreateUIButton(rectTransform, "CreditsButton", new Vector2(36f, -30f), new Vector2(20f, 10f), AbortDownloads, "Abort All"); _abortButton.ToggleWordWrapping(false); } }
private void OnLoadModelComplete(string renderModelName) { m_loadingRenderModels.Remove(renderModelName); if (loadedModelName == renderModelName) { return; } if (preferedModelName != renderModelName) { return; } if (!isActiveAndEnabled) { return; } //Debug.Log(transform.parent.parent.name + " OnLoadModelComplete " + renderModelName); ClearModel(); VIUSteamVRRenderModelLoader.RenderModel renderModel; if (!VIUSteamVRRenderModelLoader.renderModelsCache.TryGetValue(renderModelName, out renderModel)) { return; } if (loadedShader == null) { loadedShader = preferedShader; } if (renderModel.childCount == 0) { VIUSteamVRRenderModelLoader.Model model; if (VIUSteamVRRenderModelLoader.modelsCache.TryGetValue(renderModelName, out model)) { Material material; if (!m_materials.TryGetValue(model.textureID, out material)) { if (!renderModel.TryCreateMaterialForTexture(model.textureID, loadedShader, out material)) { material = new Material(loadedShader); } m_materials.Add(model.textureID, material); } m_meshFilter = gameObject.AddComponent <MeshFilter>(); m_meshFilter.mesh = model.mesh; m_meshRenderer = gameObject.AddComponent <MeshRenderer>(); m_meshRenderer.sharedMaterial = material; } } else { for (int i = 0, imax = renderModel.childCount; i < imax; ++i) { var childName = renderModel.childCompNames[i]; var modelName = renderModel.childModelNames[i]; if (string.IsNullOrEmpty(childName) || string.IsNullOrEmpty(modelName)) { continue; } if (!m_chilTransforms.ContainsKey(childName)) { var root = new GameObject(childName).transform; root.SetParent(transform, false); root.gameObject.layer = gameObject.layer; VIUSteamVRRenderModelLoader.Model model; if (VIUSteamVRRenderModelLoader.modelsCache.TryGetValue(modelName, out model)) { Material material; if (!m_materials.TryGetValue(model.textureID, out material)) { if (!renderModel.TryCreateMaterialForTexture(model.textureID, loadedShader, out material)) { material = new Material(loadedShader); } m_materials.Add(model.textureID, material); } root.gameObject.AddComponent <MeshFilter>().mesh = model.mesh; root.gameObject.AddComponent <MeshRenderer>().sharedMaterial = material; } // Also create a child 'attach' object for attaching things. var attach = new GameObject(LOCAL_TRANSFORM_NAME).transform; attach.SetParent(root, false); attach.gameObject.layer = gameObject.layer; m_chilTransforms.Add(childName, new ChildTransforms() { root = root, attach = attach, }); } } } loadedModelName = renderModelName; }
/// General entry point for checking existing connection groups of elements. protected override void CheckConnectionsInConstruction() { /// Some clean-up. if (GetComponentsInChildren <Element>(false).Length == 0) { Destroy(this.gameObject); } /// Refresh data. Reinitialize(); Transform newConstruction; Construction constrScript; /// Initialize bool array for check. isVisited = new bool[len]; bool allAreVisited = true; bool someoneWasVisited = false; bool firstTime = true; /// If we're grounded (not divided in the air)... if (groundElements != null) { /// We are trying to visit all elements from grounded ones. for (int i = 0; i < groundElements.Count; i++) { isTempVisited = new bool[len]; /// If groundElement was not visited in previous iterations... if (!isVisited[groundElements[i].index]) { CheckConnections(groundElements[i].index); } allAreVisited = true; someoneWasVisited = false; for (int j = 0; j < len; j++) { allAreVisited &= isVisited[j]; someoneWasVisited |= isTempVisited[j]; } if (allAreVisited) { /// Some clean-ups. if (GetComponentsInChildren <Element>().Length == 0) { Destroy(this.gameObject); } /// If firstTime, nothing really happens, Construction is still whole /// and we don't need to change anything. In other cases, re-initialize (for safety). if (!firstTime) { Reinitialize(); structure.connectionsFlag = true; } return; } else { /// There may be cases when we didn't fire CheckConnections() method above, /// but still getting there, so we check if there was graph bypass. if (someoneWasVisited) { /// Create new grounded construction with founded elements. newConstruction = new GameObject( "New Construction", typeof(StructConstruction) ).transform; constrScript = newConstruction.GetComponent <Construction>(); bool isRoot = true; for (int k = 0; k < len; k++) { if (isTempVisited[k]) { elements[k].transform.SetParent(newConstruction); } } /// After moving all Elements, handle information about connections. for (int k = 0; k < len; k++) { if (isTempVisited[k]) { elements[k].connections.ForEach(c => { if (c.fragment1.element.construction != c.fragment2.element.construction) { isRoot = false; } } ); if (!isRoot) { break; } } } /// If we don't reassign any connection, this construction is now floating. if (isRoot) { /// Cast to RootConstruction and reinitialize. RootConstruction rc = CastFromStructToRootConstruction(newConstruction); rc.Reinitialize(); rc.rb = rc.GetComponent <Rigidbody>(); if (rc.groundElements == null || rc.groundElements.Count == 0) { rc.rb.velocity = structure.rb.velocity; rc.rb.isKinematic = false; rc.rb.WakeUp(); } rc.rb.ResetCenterOfMass(); Destroy(newConstruction.gameObject); } else { /// Else attach us [back] to structure. newConstruction.SetParent(structure.transform); newConstruction.SetAsLastSibling(); constrScript.Reinitialize(); } } firstTime = false; } } } /// Note: we came here only if there are remaining spare elements w/o ground points. /// Now we check remaining elements (which we didn't find going from ground points). for (int i = 0; i < len; i++) { if (!isVisited[i]) { /// Found another spare element. Check its connections: isTempVisited = new bool[len]; CheckConnections(elements[i].index); /// After graph bypassing: allAreVisited = true; someoneWasVisited = false; for (int j = 0; j < len; j++) { allAreVisited &= isVisited[j]; someoneWasVisited |= isTempVisited[j]; } if (allAreVisited) { /// Maybe this condition is not needed... Just in case, okay? if (someoneWasVisited) { /// Re-new this Construction (because these elements were the last ones). Reinitialize(); } break; } else { /// And this also... But let it be, let it be~... if (someoneWasVisited) { /// Someone's remaining; after creating a Construction, search again. newConstruction = new GameObject( "New Construction", typeof(StructConstruction) ).transform; constrScript = newConstruction.GetComponent <Construction>(); bool isRoot = true; for (int k = 0; k < len; k++) { if (isTempVisited[k]) { elements[k].transform.SetParent(newConstruction); } } for (int k = 0; k < len; k++) { if (isTempVisited[k]) { elements[k].connections.ForEach(c => { if (c.fragment1.element.construction != c.fragment2.element.construction) { isRoot = false; } } ); if (!isRoot) { break; } } } /// If we don't reassign any connection, this construction is now floating. if (isRoot) { /// Cast to RootConstruction and reinitialize. RootConstruction rc = CastFromStructToRootConstruction(newConstruction); rc.Reinitialize(); rc.rb = rc.GetComponent <Rigidbody>(); if (rc.groundElements == null || rc.groundElements.Count == 0) { rc.rb.velocity = structure.rb.velocity; rc.rb.isKinematic = false; rc.rb.WakeUp(); } rc.rb.ResetCenterOfMass(); Destroy(newConstruction.gameObject); } else { /// Else attach us [back] to structure. newConstruction.SetParent(structure.transform); newConstruction.SetAsLastSibling(); constrScript.Reinitialize(); } } } } } /// Maybe we are floating now too? bool isFloating = true; for (int k = 0; k < transform.childCount; k++) { if (transform.GetChild(k).GetComponent <Element>()) { transform.GetChild(k).GetComponent <Element>().connections.ForEach(c => { if (c.fragment1.element.construction != c.fragment2.element.construction) { isFloating = false; } } ); } if (!isFloating) { break; } } if (isFloating) { /// Some clean-ups. if (GetComponentsInChildren <Element>().Length == 0) { Destroy(this.gameObject); } /// Cast to RootElement and reinitialize. RootConstruction rc = CastFromStructToRootConstruction(transform); rc.Reinitialize(); rc.rb = rc.GetComponent <Rigidbody>(); if (rc.groundElements == null || rc.groundElements.Count == 0) { rc.rb.velocity = structure.rb.velocity; rc.rb.isKinematic = false; rc.rb.WakeUp(); } rc.rb.ResetCenterOfMass(); Destroy(this.gameObject); } /// Now we can check further. structure.connectionsFlag = true; /// Some clean-ups. if (GetComponentsInChildren <Element>().Length == 0) { Destroy(this.gameObject); } }
private void SetUpSpawners(Level level) { Debug.Log("Set Up Spawners"); Transform levelSpawnersTransform = new GameObject("Level " + level.levelName + " Spawners").transform; levelSpawnersTransform.SetParent(spawnerParent); for (int i = 0; i < level.spawners.Count; i++) { Spawner spawner = Instantiate(level.spawners[i]) as Spawner; Debug.Log(spawner + " created"); spawner.transform.SetParent(levelSpawnersTransform); createdSpawners.Add(spawner); } SpawnManager.Instance.SetUpLevel(level.initialSpawnDirection); }
protected override void DidActivate(bool firstActivation, ActivationType type) { if (firstActivation && type == ActivationType.AddedToHierarchy) { _serverTableCellInstance = Resources.FindObjectsOfTypeAll <LevelListTableCell>().First(x => (x.name == "LevelListTableCell")); _pageUpButton = Instantiate(Resources.FindObjectsOfTypeAll <Button>().Last(x => (x.name == "PageUpButton")), rectTransform, false); (_pageUpButton.transform as RectTransform).anchorMin = new Vector2(0.5f, 1f); (_pageUpButton.transform as RectTransform).anchorMax = new Vector2(0.5f, 1f); (_pageUpButton.transform as RectTransform).anchoredPosition = new Vector2(0f, -4.5f); (_pageUpButton.transform as RectTransform).sizeDelta = new Vector2(40f, 10f); _pageUpButton.interactable = true; _pageUpButton.onClick.AddListener(delegate() { _serverTableView.GetPrivateField <TableViewScroller>("_scroller").PageScrollUp(); }); _pageDownButton = Instantiate(Resources.FindObjectsOfTypeAll <Button>().First(x => (x.name == "PageDownButton")), rectTransform, false); (_pageDownButton.transform as RectTransform).anchorMin = new Vector2(0.5f, 0f); (_pageDownButton.transform as RectTransform).anchorMax = new Vector2(0.5f, 0f); (_pageDownButton.transform as RectTransform).anchoredPosition = new Vector2(0f, -1f); (_pageDownButton.transform as RectTransform).sizeDelta = new Vector2(40f, 10f); _pageDownButton.interactable = true; _pageDownButton.onClick.AddListener(delegate() { _serverTableView.GetPrivateField <TableViewScroller>("_scroller").PageScrollDown(); }); _refreshButton = this.CreateUIButton("PracticeButton", new Vector2(-25f, 36.5f), new Vector2(6.5f, 6.5f), () => { refreshPressed?.Invoke(); }, "", Sprites.refreshIcon); var _refreshIconLayout = _refreshButton.GetComponentsInChildren <HorizontalLayoutGroup>().First(x => x.name == "Content"); _refreshIconLayout.padding = new RectOffset(0, 0, 1, 1); _createRoom = BeatSaberUI.CreateUIButton(rectTransform, "CancelButton"); _createRoom.SetButtonText("Create room"); _createRoom.SetButtonTextSize(3f); (_createRoom.transform as RectTransform).sizeDelta = new Vector2(38f, 6f); (_createRoom.transform as RectTransform).anchoredPosition = new Vector2(0f, 36.5f); _createRoom.onClick.RemoveAllListeners(); _createRoom.onClick.AddListener(delegate() { createRoomButtonPressed?.Invoke(); }); RectTransform container = new GameObject("Container", typeof(RectTransform)).transform as RectTransform; container.SetParent(rectTransform, false); container.anchorMin = new Vector2(0.3f, 0.5f); container.anchorMax = new Vector2(0.7f, 0.5f); container.sizeDelta = new Vector2(0f, 60f); container.anchoredPosition = new Vector2(0f, -3f); var tableGameObject = new GameObject("CustomTableView"); tableGameObject.SetActive(false); _serverTableView = tableGameObject.AddComponent <TableView>(); _serverTableView.gameObject.AddComponent <RectMask2D>(); _serverTableView.transform.SetParent(container, false); _serverTableView.SetPrivateField("_isInitialized", false); _serverTableView.SetPrivateField("_preallocatedCells", new TableView.CellsGroup[0]); RectTransform viewport = new GameObject("Viewport").AddComponent <RectTransform>(); viewport.SetParent(_serverTableView.transform, false); (viewport.transform as RectTransform).sizeDelta = new Vector2(0f, 0f); (viewport.transform as RectTransform).anchorMin = new Vector2(0f, 0f); (viewport.transform as RectTransform).anchorMax = new Vector2(1f, 1f); _serverTableView.GetComponent <ScrollRect>().viewport = viewport; _serverTableView.Init(); (_serverTableView.transform as RectTransform).anchorMin = new Vector2(0f, 0f); (_serverTableView.transform as RectTransform).anchorMax = new Vector2(1f, 1f); (_serverTableView.transform as RectTransform).sizeDelta = new Vector2(0f, 0f); (_serverTableView.transform as RectTransform).anchoredPosition = new Vector3(0f, 0f); tableGameObject.SetActive(true); _serverTableView.didSelectCellWithIdxEvent += ServerTableView_DidSelectRow; _serverTableView.dataSource = this; } else { _serverTableView.ReloadData(); } }
public void Button_MakeIt() { Mesh _mesh = GetComponent <MeshFilter>().sharedMesh; MeshRenderer _renderer = GetComponent <MeshRenderer>(); Mesh[] _made_meshes = new Mesh[_mesh.subMeshCount]; // go through the sub indices for (int sub = 0; sub < _mesh.subMeshCount; sub++) { Mesh_Maker maker = new Mesh_Maker(); int[] trinagles = _mesh.GetTriangles(sub); // go through the triangles for (int i = 0; i < trinagles.Length; i += 3) { maker.AddTriangle(new Vector3[] { _mesh.vertices[trinagles[i]], _mesh.vertices[trinagles[i + 1]], _mesh.vertices[trinagles[i + 2]] }, new Vector2[] { _mesh.uv[trinagles[i]], _mesh.uv[trinagles[i + 1]], _mesh.uv[trinagles[i + 2]] }, new Vector3[] { _mesh.normals[trinagles[i]], _mesh.normals[trinagles[i + 1]], _mesh.normals[trinagles[i + 2]] }, 0); } maker.RemoveDoubles(); _made_meshes[sub] = maker.GetMesh(); } // too many while (transform.childCount > _mesh.subMeshCount) { Transform obj = transform.GetChild(transform.childCount - 1); obj.parent = null; DestroyImmediate(obj.gameObject); } // too little while (transform.childCount < _mesh.subMeshCount) { Transform obj = new GameObject("child").transform; obj.SetParent(transform); obj.localPosition = Vector3.zero; obj.localRotation = Quaternion.identity; obj.gameObject.AddComponent <MeshCollider>(); } for (int i = 0; i < transform.childCount; i++) { Transform obj = transform.GetChild(i); obj.gameObject.name = _renderer.sharedMaterials[i].name; _made_meshes[i].name = obj.gameObject.name; obj.GetComponent <MeshCollider>().sharedMesh = _made_meshes[i]; } }
/// <summary> /// Called when <see cref="BasicGadgetConfigMenu.Build"/> is called on the config menu containing this component. /// </summary> public override void Build(RectTransform parent) { if (!string.IsNullOrEmpty(Name)) { StringBuilder nameString = new StringBuilder(); int spacesAdded = 0; foreach (char c in Name) { if (nameString.Length > 0 && char.IsUpper(c) && !char.IsUpper(Name[nameString.Length - spacesAdded - 1]) && (Name.Length == 1 || !char.IsUpper(Name[nameString.Length - spacesAdded - 2]) || (Name.Length > 2 && !char.IsUpper(Name[nameString.Length - spacesAdded - 3])))) { spacesAdded++; nameString.Append(' '); } nameString.Append(nameString.Length > 0 ? c : char.ToUpper(c)); } Text label = new GameObject("Label", typeof(RectTransform), typeof(CanvasRenderer), typeof(Text)).GetComponent <Text>(); label.rectTransform.SetParent(parent); label.rectTransform.anchorMin = new Vector2(0f, 0f); label.rectTransform.anchorMax = new Vector2(0.25f, 1f); label.rectTransform.offsetMin = new Vector2(0, 0); label.rectTransform.offsetMax = new Vector2(-10, 0); label.text = nameString + ":"; label.font = SceneInjector.ModConfigMenuText.GetComponent <TextMesh>().font; label.fontSize = 12; label.horizontalOverflow = HorizontalWrapMode.Wrap; label.alignment = TextAnchor.MiddleLeft; } InputField textbox = new GameObject("Textbox", typeof(RectTransform), typeof(CanvasRenderer), typeof(Image), typeof(InputField)).GetComponent <InputField>(); textbox.GetComponent <RectTransform>().SetParent(parent); textbox.GetComponent <RectTransform>().anchorMin = new Vector2(0.25f, 0f); textbox.GetComponent <RectTransform>().anchorMax = new Vector2(0.5f, 1f); textbox.GetComponent <RectTransform>().offsetMin = new Vector2(10f, 0f); textbox.GetComponent <RectTransform>().offsetMax = new Vector2(0f, 0f); textbox.GetComponent <Image>().sprite = SceneInjector.BoxSprite; textbox.GetComponent <Image>().type = Image.Type.Sliced; textbox.GetComponent <Image>().fillCenter = true; Text placeholder = new GameObject("Placeholder", typeof(RectTransform), typeof(CanvasRenderer), typeof(Text)).GetComponent <Text>(); placeholder.rectTransform.SetParent(textbox.transform); placeholder.rectTransform.anchorMin = new Vector2(0f, 0f); placeholder.rectTransform.anchorMax = new Vector2(1f, 1f); placeholder.rectTransform.offsetMin = new Vector2(10f, 0f); placeholder.rectTransform.offsetMax = new Vector2(-10f, 0f); placeholder.text = (DefaultValue != null ? "Default: " + DefaultValue + " " : "") + (VanillaValue != null ? "Vanilla: " + VanillaValue : ""); placeholder.font = SceneInjector.ModConfigMenuText.GetComponent <TextMesh>().font; placeholder.fontSize = 12; placeholder.horizontalOverflow = HorizontalWrapMode.Wrap; placeholder.alignment = TextAnchor.MiddleLeft; placeholder.color = new Color(1f, 1f, 1f, 0.5f); textbox.placeholder = placeholder; Text text = new GameObject("Text", typeof(RectTransform), typeof(CanvasRenderer), typeof(Text)).GetComponent <Text>(); text.rectTransform.SetParent(textbox.transform); text.rectTransform.anchorMin = new Vector2(0f, 0f); text.rectTransform.anchorMax = new Vector2(1f, 1f); text.rectTransform.offsetMin = new Vector2(10f, 0f); text.rectTransform.offsetMax = new Vector2(-10f, 0f); text.font = SceneInjector.ModConfigMenuText.GetComponent <TextMesh>().font; text.fontSize = 12; text.horizontalOverflow = HorizontalWrapMode.Wrap; text.supportRichText = true; text.alignment = TextAnchor.MiddleLeft; textbox.textComponent = text; textbox.readOnly = ReadOnly; textbox.interactable = !ReadOnly; textbox.text = Value.ToString(); textbox.characterValidation = InputField.CharacterValidation.Decimal; if (MaxValue > MinValue && MinValue > double.MinValue && MaxValue < double.MaxValue) { Slider slider = new GameObject("Slider", typeof(RectTransform), typeof(Slider)).GetComponent <Slider>(); slider.transform.SetParent(parent); slider.GetComponent <RectTransform>().anchorMin = new Vector2(0.5f, 0.5f); slider.GetComponent <RectTransform>().anchorMax = new Vector2(1f, 0.5f); slider.GetComponent <RectTransform>().offsetMin = new Vector2(10f, -10f); slider.GetComponent <RectTransform>().offsetMax = new Vector2(-10f, 10f); Image sliderBackground = new GameObject("Background", typeof(RectTransform), typeof(CanvasRenderer), typeof(Image)).GetComponent <Image>(); sliderBackground.rectTransform.SetParent(slider.transform); sliderBackground.rectTransform.anchorMin = new Vector2(0f, 0.25f); sliderBackground.rectTransform.anchorMax = new Vector2(1f, 0.75f); sliderBackground.rectTransform.offsetMin = new Vector2(10f, 0f); sliderBackground.rectTransform.offsetMax = new Vector2(0f, 0f); sliderBackground.sprite = SceneInjector.BoxSprite; sliderBackground.type = Image.Type.Sliced; sliderBackground.fillCenter = true; RectTransform sliderHandleArea = new GameObject("Handle Slide Area", typeof(RectTransform)).GetComponent <RectTransform>(); sliderHandleArea.SetParent(slider.transform); sliderHandleArea.anchorMin = Vector2.zero; sliderHandleArea.anchorMax = Vector2.one; sliderHandleArea.offsetMin = new Vector2(10f, 0f); sliderHandleArea.offsetMax = new Vector2(0f, 0f); Image sliderHandle = new GameObject("Handle", typeof(RectTransform), typeof(CanvasRenderer), typeof(Image)).GetComponent <Image>(); sliderHandle.rectTransform.SetParent(sliderHandleArea); sliderHandle.rectTransform.anchorMin = new Vector2(0f, 0f); sliderHandle.rectTransform.anchorMax = new Vector2(0f, 1f); sliderHandle.rectTransform.offsetMin = new Vector2(-10f, 0f); sliderHandle.rectTransform.offsetMax = new Vector2(10f, 0f); sliderHandle.sprite = SceneInjector.BoxSprite; sliderHandle.type = Image.Type.Sliced; sliderHandle.fillCenter = true; slider.minValue = (float)MinValue; slider.maxValue = (float)MaxValue; slider.wholeNumbers = false; slider.value = (float)Value; slider.handleRect = sliderHandle.rectTransform; slider.onValueChanged.AddListener((value) => { Value = Decimals > -1 ? Math.Round(value, Decimals) : value; Value = Value <MinValue?MinValue : Value> MaxValue ? MaxValue : Value; textbox.text = Value.ToString(); slider.value = (float)Value; ValueSetter(Value); }); textbox.onEndEdit.AddListener((value) => { if (!string.IsNullOrEmpty(value)) { if (double.TryParse(value, out double parsedValue)) { Value = Decimals > -1 ? Math.Round(double.Parse(value), Decimals) : double.Parse(value); Value = Value <MinValue?MinValue : Value> MaxValue ? MaxValue : Value; textbox.text = Value.ToString(); slider.value = (float)Value; ValueSetter(Value); } else { textbox.text = value[0] == '-' ? MinValue.ToString() : MaxValue.ToString(); } } }); } else { textbox.onEndEdit.AddListener((value) => { if (!string.IsNullOrEmpty(value)) { if (double.TryParse(value, out double parsedValue)) { Value = Decimals > -1 ? Math.Round(double.Parse(value), Decimals) : double.Parse(value); if (MaxValue > MinValue) { Value = Value <MinValue?MinValue : Value> MaxValue ? MaxValue : Value; } textbox.text = Value.ToString(); ValueSetter(Value); } else { textbox.text = value[0] == '-' ? MaxValue > MinValue ? MinValue.ToString() : double.MinValue.ToString() : MaxValue > MinValue ? MaxValue.ToString() : double.MinValue.ToString(); } } }); } }
public void RemoveChild(GameObject child) { children.Remove(child); child.SetParent(null); child.Update(renderManager); }
public void ResetLocks() { // create new locks/medals if necessary if (unlockedLevels==null || unlockedLevels.Count==0 || locks.Count==0) { unlockedLevels = new HashSet<int>(_unlockedLevels); brokenLevels = new HashSet<int>(_brokenLevels); for (int i=0; i<levels.Count; ++i) { RectTransform t = levels[i].GetComponent<RectTransform>(); RectTransform levelLock = new GameObject("Level "+(i+1)+" Lock").AddComponent<RectTransform>(); levelLock.SetParent(t.parent); levelLock.sizeDelta = t.sizeDelta; levelLock.localScale = t.localScale; levelLock.localPosition = t.localPosition; levelLock.SetParent(t); Image img = levelLock.gameObject.AddComponent<Image>(); img.sprite = locked; locks.Add(levelLock); RectTransform medal = new GameObject("Level "+(i+1)+" Medal").AddComponent<RectTransform>(); medal.SetParent(t.parent); medal.sizeDelta = t.sizeDelta/2; medal.localScale = medalSize; medal.localPosition = t.localPosition + medalOffset; medal.SetParent(t); medal.gameObject.AddComponent<Image>(); medals.Add(medal); medal.gameObject.SetActive(false); } } // lock all levels for (int i=0; i<levels.Count; ++i) UnlockLevel(i, false); // unlock preselected levels for (int i=0; i<levels.Count; ++i) { if (unlockedLevels.Contains(i+1)) { for (int remaining=1; i<levels.Count&&remaining>0; ++i) { if (unlockedLevels.Contains(i+2)) ++remaining; if (brokenLevels.Contains(i+1)) continue; if (PlayerPrefs.HasKey("Level "+(i+1))) ++remaining; UnlockLevel(i, true); --remaining; } } } // unlock special levels bool l46=true, l48=true, l49=true; for (int i=0; i<14; ++i) l46 = l46 && PlayerPrefs.HasKey("Level "+(i+1)); for (int i=0; i<15; ++i) l48 = l48 && PlayerPrefs.HasKey("Level "+(i+16)); for (int i=0; i<10; ++i) l49 = l49 && PlayerPrefs.HasKey("Level "+(i+31)); UnlockLevel(45, l46); UnlockLevel(46, PlayerPrefs.HasKey("Level 46")); UnlockLevel(47, false);//l48); UnlockLevel(48, l49); UnlockLevel(49, PlayerPrefs.HasKey("Level 47") /*&& PlayerPrefs.HasKey("Level 48")*/ && PlayerPrefs.HasKey("Level 49")); // add medals for (int i=0; i<levels.Count; ++i) { if (!locks[i].gameObject.activeSelf) { float time = PlayerPrefs.GetFloat("Level "+(i+1)); float bronze = PlayerPrefs.GetFloat("Level "+(i+1)+" Bronze"); float silver = PlayerPrefs.GetFloat("Level "+(i+1)+" Silver"); float gold = PlayerPrefs.GetFloat("Level "+(i+1)+" Gold"); if (time!=0) medals[i].gameObject.SetActive(true); if (time>bronze || time==0) medals[i].gameObject.SetActive(false); if (time<=bronze && time!=0) medals[i].GetComponent<Image>().sprite = this.bronze; if (time<=silver && time!=0) medals[i].GetComponent<Image>().sprite = this.silver; if (time<=gold && time!=0) medals[i].GetComponent<Image>().sprite = this.gold; } } }
public void AddChild(GameObject child) { children.Add(child); child.SetParent(this); }
CanvasElement GetNewLayer(string name) { var newLayer = new GameObject(name).AddComponent<RectTransform>(); newLayer.anchorMin = Vector2.zero; newLayer.anchorMax = Vector2.one; newLayer.sizeDelta = Vector2.zero; newLayer.SetParent(BranchRoot.transform, false); return new CanvasElement(newLayer); }
void CreateGraph() { Transform graphTransform = new GameObject("Graph").transform; // for organisation graphTransform.SetParent(transform); graph = new Graph(graphTransform); graph.AddLine("grass", Color.green); graph.AddLine("oak tree", Color.black); graph.AddLine("berries", Color.magenta); graph.AddLine("rabbit", Color.grey); graph.AddLine("caterpillar", Color.yellow); graph.AddLine("squirrel", Color.white); graph.AddLine("fox", Color.red); // TODO: scale this according to screen width InvokeRepeating("UpdateGraph", 0.5f, 0.5f); }
private void createMonsters() { if (monsters.Length == 0) { Debug.LogError("No monsters defined!"); return; } GameObject[] floorTiles = GameObject.FindGameObjectsWithTag("Floor"); if (floorTiles.Length == 0) { Debug.LogError("Not a single floor tile to put monsters!"); return; } // Only take the tiles that are far enough from the hero List<GameObject> floorTilesToPutMonster = new List<GameObject>(); foreach (GameObject tile in floorTiles) { if ((tile.transform.position - hero.transform.position).magnitude > 10) // Arbritrary safe distance value (greater than vision distance of mobs) floorTilesToPutMonster.Add(tile); } Transform monsterHolder = new GameObject("Monsters").transform; monsterHolder.SetParent(levelMap.transform); for (int i = 0; i < monsterNumber; i++) { Vector3 positionToPutMonster = Utils.pickRandom(floorTilesToPutMonster).transform.position; GameObject newMonster = Instantiate(Utils.pickRandom(monsters), positionToPutMonster, Quaternion.identity) as GameObject; newMonster.transform.SetParent(monsterHolder); newMonster.GetComponent<MonsterController>().Initialize(levelMap); } }
private static Transform SyncKernel(MVVMNode node, GameObject uFrameMVVMKernel) { var servicesContainer = uFrameMVVMKernel.transform.FindChild("Services"); if (servicesContainer == null) { servicesContainer = new GameObject("Services").transform; servicesContainer.SetParent(uFrameMVVMKernel.transform); } var systemLoadersContainer = uFrameMVVMKernel.transform.FindChild("SystemLoaders"); if (systemLoadersContainer == null) { systemLoadersContainer = new GameObject("SystemLoaders").transform; systemLoadersContainer.SetParent(uFrameMVVMKernel.transform); } var sceneLoaderContainer = uFrameMVVMKernel.transform.FindChild("SceneLoaders"); if (sceneLoaderContainer == null) { sceneLoaderContainer = new GameObject("SceneLoaders").transform; sceneLoaderContainer.SetParent(uFrameMVVMKernel.transform); } //var servicesNodes = InvertApplication.Container.Resolve<WorkspaceService>().CurrentWorkspace.Graphs // .SelectMany(g => g.AllGraphItems.OfType<ServiceNode>()); var servicesNodes = InvertApplication.Container.Resolve <WorkspaceService>() .Workspaces.SelectMany(w => w.Graphs) .SelectMany(g => g.AllGraphItems.OfType <ServiceNode>()); foreach (var serviceNode in servicesNodes) { //var type = InvertApplication.FindType(serviceNode.FullName); var type = InvertApplication.FindRuntimeType(serviceNode.FullName); if (type != null && servicesContainer.GetComponent(type) == null) { servicesContainer.gameObject.AddComponent(type); } } //var systemNodes = InvertApplication.Container.Resolve<WorkspaceService>().CurrentWorkspace.Graphs // .SelectMany(g => g.AllGraphItems.OfType<SubSystemNode>()); var systemNodes = InvertApplication.Container.Resolve <WorkspaceService>() .Workspaces.SelectMany(w => w.Graphs) .SelectMany(g => g.AllGraphItems.OfType <SubSystemNode>()); foreach (var systemNode in systemNodes) { //var type = InvertApplication.FindType(string.Format("{0}Loader", systemNode.FullName)); var type = InvertApplication.FindRuntimeType(string.Format("{0}Loader", systemNode.FullName)); if (type != null && systemLoadersContainer.GetComponent(type) == null) { systemLoadersContainer.gameObject.AddComponent(type); } } //var sceneNodes = node.Graph.AllGraphItems.OfType<SceneTypeNode>(); var sceneNodes = InvertApplication.Container.Resolve <WorkspaceService>() .Workspaces.SelectMany(w => w.Graphs) .SelectMany(g => g.AllGraphItems.OfType <SceneTypeNode>()); foreach (var sceneNode in sceneNodes) { //var type = InvertApplication.FindType(string.Format("{0}Loader", sceneNode.FullName)); var type = InvertApplication.FindRuntimeType(string.Format("{0}Loader", sceneNode.FullName)); if (type != null && sceneLoaderContainer.GetComponent(type) == null) { sceneLoaderContainer.gameObject.AddComponent(type); } } EditorUtility.SetDirty(uFrameMVVMKernel); return(servicesContainer); }
public static Transform AddChild(this Transform tr, GameObject child) { child.SetParent(tr); return(tr); }
public void SetupRig() { var rigAnimator = this.GetComponent <Animator>(); var rigNameToTransform = new Dictionary <string, Transform>(); var humanNameToBoneName = new Dictionary <string, string>(); // Making a quick dictionary lookup for transforms and their names foreach (var transform in this.root.GetComponentsInChildren <Transform>()) { rigNameToTransform.Add(transform.name, transform); } // Setting up the Bone Renderer var boneTransforms = new List <Transform>(); foreach (var humanBone in rigAnimator.avatar.humanDescription.human) { humanNameToBoneName.Add(humanBone.humanName, humanBone.boneName); boneTransforms.Add(rigNameToTransform[humanBone.boneName]); } var boneRenderer = GetOrAddComponentToGameObject <BoneRenderer>(this.gameObject); boneRenderer.transforms = boneTransforms.ToArray(); // Setting up Rig var vrConstraints = GetOrCreateChildGameObject(this.gameObject, "VR Constraints"); var rig = GetOrAddComponentToGameObject <Rig>(vrConstraints); // Setting up Rig Builder var rigBuilder = GetOrAddComponentToGameObject <RigBuilder>(this.gameObject); if (rigBuilder.layers == null || rigBuilder.layers.Count == 0 || rigBuilder.layers[0].rig != rig) { rigBuilder.layers = new List <RigLayer> { new RigLayer(rig) }; } // Setting Two Bone IK Constraints (Arms) SetupTwoBoneContraint(vrConstraints, "Right Arm IK", "RightUpperArm", "RightLowerArm", "RightHand", this.rightHand); SetupTwoBoneContraint(vrConstraints, "LeftArm IK", "LeftUpperArm", "LeftLowerArm", "LeftHand", this.leftHand); // Setting up Head Constraint var headBone = rigNameToTransform[humanNameToBoneName["Head"]]; var headConstraint = GetOrCreateChildGameObject(vrConstraints, "Head Constraint"); headConstraint.transform.SetPositionAndRotation(headBone.position, headBone.rotation); var multiParentConstraint = GetOrAddComponentToGameObject <MultiParentConstraint>(headConstraint); multiParentConstraint.data.constrainedObject = headBone; multiParentConstraint.data.sourceObjects = new WeightedTransformArray { new WeightedTransform { transform = headConstraint.transform, weight = 1.0f }, }; // Storing Head Constraint for Start/LateUpdate function this.headConstraint = headConstraint.transform; void SetupTwoBoneContraint(GameObject parent, string gameObjectName, string rootName, string midName, string tipName, VRMap vrMap) { var armIk = GetOrCreateChildGameObject(parent, gameObjectName); var armIkConstraint = GetOrAddComponentToGameObject <TwoBoneIKConstraint>(armIk); armIkConstraint.data.root = rigNameToTransform[humanNameToBoneName[rootName]]; armIkConstraint.data.mid = rigNameToTransform[humanNameToBoneName[midName]]; armIkConstraint.data.tip = rigNameToTransform[humanNameToBoneName[tipName]]; // Setup Target var target = GetOrCreateChildGameObject(armIk, "Target"); target.transform.SetPositionAndRotation(armIkConstraint.data.tip.position, armIkConstraint.data.tip.rotation); armIkConstraint.data.target = target.transform; // Setup Hint Vector3 rootToMid = armIkConstraint.data.root.position - armIkConstraint.data.mid.position; Vector3 tipToMid = armIkConstraint.data.tip.position - armIkConstraint.data.mid.position; Vector3 average = (rootToMid.normalized + tipToMid.normalized) / -2.0f; Vector3 hintPosition = armIkConstraint.data.mid.position + (average * 0.1f); var hint = GetOrCreateChildGameObject(armIk, "Hint"); hint.transform.position = hintPosition; armIkConstraint.data.hint = hint.transform; // Updating VR Map object vrMap.RigTarget = target.transform; } T GetOrAddComponentToGameObject <T>(GameObject gameObject) where T : Component { var component = gameObject.GetComponent <T>(); if (component == null) { return(gameObject.AddComponent <T>()); } return(component); } GameObject GetOrCreateChildGameObject(GameObject gameObject, string name) { var childTransform = gameObject.transform.Find(name); if (childTransform == null) { childTransform = new GameObject(name).transform; childTransform.SetParent(gameObject.transform); childTransform.SetPositionAndRotation(Vector3.zero, Quaternion.identity); childTransform.localScale = Vector3.one; } return(childTransform.gameObject); } }
public void AlignTestItem() { if (grabItem) { grabHandle = ragdollHand.side == Side.Right ? grabItem.mainHandleRight : grabItem.mainHandleLeft; } if (!grabHandle) { return; } if (previousHandle && previousHandle != grabHandle) { Item previousItem = previousHandle.GetComponentInParent <Item>(); if (previousItem) { previousItem.transform.localPosition = new Vector3(0, 100, 0); previousItem.transform.localRotation = Quaternion.identity; } else { previousHandle.transform.root.localPosition = new Vector3(0, 100, 0); previousHandle.transform.root.localRotation = Quaternion.identity; } } if (useGripFrom == Grip.OpenPose) { ragdollHand.SetGripFromOpenPose(); } else if (useGripFrom == Grip.ClosePose) { ragdollHand.SetGripFromClosePose(); } grabHandle.CheckOrientations(); HandleOrientation handleOrientation = grabHandle.orientationDefaultRight; if (ragdollHand.side == Side.Left) { handleOrientation = grabHandle.orientationDefaultLeft; } if (handleOrientationIndex > 0) { int i = 0; foreach (HandleOrientation ho in grabHandle.orientations) { if (grabHandle.orientationDefaultLeft == ho) { continue; } if (grabHandle.orientationDefaultRight == ho) { continue; } if (ho.side == ragdollHand.side) { if ((handleOrientationIndex - 1) == i) { handleOrientation = ho; } i++; } } } Item item = grabHandle.GetComponentInParent <Item>(); Transform alignObject = grabHandle.transform.root; if (item != null) { alignObject = item.transform; } Transform objectGrip = new GameObject("ObjectGrip").transform; objectGrip.SetParent(item ? item.transform : grabHandle.transform.root); objectGrip.position = handleOrientation.transform.position + (handleOrientation.handle.transform.up * handleOrientation.handle.GetDefaultAxisLocalPosition()); objectGrip.rotation = handleOrientation.transform.rotation; alignObject.MoveAlign(objectGrip, ragdollHand.grip.position, ragdollHand.grip.rotation); DestroyImmediate(objectGrip.gameObject); previousHandle = grabHandle; }
/// <summary> /// Called when <see cref="BasicGadgetConfigMenu.Build"/> is called on the config menu containing this component. /// </summary> public override void Build(RectTransform parent) { if (!string.IsNullOrEmpty(Name)) { StringBuilder nameString = new StringBuilder(); int spacesAdded = 0; foreach (char c in Name) { if (nameString.Length > 0 && char.IsUpper(c) && !char.IsUpper(Name[nameString.Length - spacesAdded - 1]) && (Name.Length == 1 || !char.IsUpper(Name[nameString.Length - spacesAdded - 2]) || (Name.Length > 2 && !char.IsUpper(Name[nameString.Length - spacesAdded - 3])))) { spacesAdded++; nameString.Append(' '); } nameString.Append(nameString.Length > 0 ? c : char.ToUpper(c)); } Text label = new GameObject("Label", typeof(RectTransform), typeof(CanvasRenderer), typeof(Text)).GetComponent <Text>(); label.rectTransform.SetParent(parent); label.rectTransform.anchorMin = new Vector2(0f, 0f); label.rectTransform.anchorMax = new Vector2(0.25f, 1f); label.rectTransform.offsetMin = new Vector2(0, 0); label.rectTransform.offsetMax = new Vector2(-10, 0); label.text = nameString + ":"; label.font = SceneInjector.ModConfigMenuText.GetComponent <TextMesh>().font; label.fontSize = 12; label.horizontalOverflow = HorizontalWrapMode.Wrap; label.alignment = TextAnchor.MiddleLeft; } Text defaults = new GameObject("Defaults", typeof(RectTransform), typeof(CanvasRenderer), typeof(Text)).GetComponent <Text>(); defaults.rectTransform.SetParent(parent); defaults.rectTransform.anchorMin = new Vector2(0.5f, 0f); defaults.rectTransform.anchorMax = new Vector2(1f, 1f); defaults.rectTransform.offsetMin = new Vector2(10, 0); defaults.rectTransform.offsetMax = new Vector2(0, 0); defaults.text = (DefaultValue != null ? "Default: " + DefaultValue + " " : "") + (VanillaValue != null ? "Vanilla: " + VanillaValue : ""); defaults.font = SceneInjector.ModConfigMenuText.GetComponent <TextMesh>().font; defaults.fontSize = 12; defaults.horizontalOverflow = HorizontalWrapMode.Wrap; defaults.alignment = TextAnchor.MiddleLeft; ToggleGroup toggleGroup = new GameObject("ToggleGroup", typeof(RectTransform), typeof(ToggleGroup)).GetComponent <ToggleGroup>(); toggleGroup.GetComponent <RectTransform>().SetParent(parent); toggleGroup.GetComponent <RectTransform>().anchorMin = new Vector2(0.25f, 0f); toggleGroup.GetComponent <RectTransform>().anchorMax = new Vector2(0.5f, 1f); toggleGroup.GetComponent <RectTransform>().offsetMin = new Vector2(10, 0); toggleGroup.GetComponent <RectTransform>().offsetMax = new Vector2(-10, 0); RectTransform trueButton = new GameObject("True", typeof(RectTransform), typeof(Toggle), typeof(CanvasRenderer), typeof(Image), typeof(Mask)).GetComponent <RectTransform>(); trueButton.SetParent(toggleGroup.transform); trueButton.anchorMin = new Vector2(0f, 0f); trueButton.anchorMax = new Vector2(Math.Max(Math.Min(Height * 3f, 0.5f), 0.25f), 1f); trueButton.offsetMin = new Vector2(0, 0); trueButton.offsetMax = new Vector2(-2.5f, 0); Toggle trueToggle = trueButton.GetComponent <Toggle>(); Image trueSelected = new GameObject("Selected", typeof(RectTransform), typeof(CanvasRenderer), typeof(Image)).GetComponent <Image>(); trueSelected.rectTransform.SetParent(trueButton); trueSelected.rectTransform.anchorMin = new Vector2(0f, 0f); trueSelected.rectTransform.anchorMax = new Vector2(1f, 1f); trueSelected.rectTransform.offsetMin = Vector2.zero; trueSelected.rectTransform.offsetMax = Vector2.zero; trueSelected.sprite = SceneInjector.BoxSprite; trueSelected.type = Image.Type.Sliced; Text trueLabel = new GameObject("Label", typeof(RectTransform), typeof(CanvasRenderer), typeof(Text)).GetComponent <Text>(); trueLabel.rectTransform.SetParent(trueButton); trueLabel.rectTransform.anchorMin = new Vector2(0f, 0f); trueLabel.rectTransform.anchorMax = new Vector2(1f, 1f); trueLabel.rectTransform.offsetMin = new Vector2(2.5f, 2.5f); trueLabel.rectTransform.offsetMax = new Vector2(-2.5f, -2.5f); trueLabel.font = SceneInjector.ModConfigMenuText.GetComponent <TextMesh>().font; trueLabel.horizontalOverflow = HorizontalWrapMode.Overflow; trueLabel.verticalOverflow = VerticalWrapMode.Overflow; trueLabel.alignment = TextAnchor.MiddleCenter; trueLabel.text = "T"; trueToggle.GetComponent <Image>().sprite = SceneInjector.BoxSprite; trueToggle.GetComponent <Image>().type = Image.Type.Sliced; trueToggle.GetComponent <Image>().color = new Color(1f, 1f, 1f, 0.25f); trueToggle.transition = Selectable.Transition.None; trueToggle.isOn = Value; trueToggle.interactable = !ReadOnly; trueToggle.toggleTransition = Toggle.ToggleTransition.None; trueToggle.graphic = trueSelected; trueToggle.group = toggleGroup; trueToggle.onValueChanged.AddListener((toggled) => { if (toggled) { ValueSetter(true); } }); RectTransform falseButton = new GameObject("False", typeof(RectTransform), typeof(Toggle), typeof(CanvasRenderer), typeof(Image), typeof(Mask)).GetComponent <RectTransform>(); falseButton.SetParent(toggleGroup.transform); falseButton.anchorMin = new Vector2(Math.Max(Math.Min(Height * 3f, 0.5f), 0.25f), 0f); falseButton.anchorMax = new Vector2(Math.Max(Math.Min(Height * 3f, 0.5f), 0.25f) * 2, 1f); falseButton.offsetMin = new Vector2(2.5f, 0); falseButton.offsetMax = new Vector2(0, 0); Toggle falseToggle = falseButton.GetComponent <Toggle>(); Image falseSelected = new GameObject("Selected", typeof(RectTransform), typeof(CanvasRenderer), typeof(Image)).GetComponent <Image>(); falseSelected.rectTransform.SetParent(falseButton); falseSelected.rectTransform.anchorMin = new Vector2(0f, 0f); falseSelected.rectTransform.anchorMax = new Vector2(1f, 1f); falseSelected.rectTransform.offsetMin = Vector2.zero; falseSelected.rectTransform.offsetMax = Vector2.zero; falseSelected.sprite = SceneInjector.BoxSprite; falseSelected.type = Image.Type.Sliced; Text falseLabel = new GameObject("Label", typeof(RectTransform), typeof(CanvasRenderer), typeof(Text)).GetComponent <Text>(); falseLabel.rectTransform.SetParent(falseButton); falseLabel.rectTransform.anchorMin = new Vector2(0f, 0f); falseLabel.rectTransform.anchorMax = new Vector2(1f, 1f); falseLabel.rectTransform.offsetMin = new Vector2(2.5f, 2.5f); falseLabel.rectTransform.offsetMax = new Vector2(-2.5f, -2.5f); falseLabel.font = SceneInjector.ModConfigMenuText.GetComponent <TextMesh>().font; falseLabel.horizontalOverflow = HorizontalWrapMode.Overflow; falseLabel.verticalOverflow = VerticalWrapMode.Overflow; falseLabel.alignment = TextAnchor.MiddleCenter; falseLabel.text = "F"; falseToggle.GetComponent <Image>().sprite = SceneInjector.BoxSprite; falseToggle.GetComponent <Image>().type = Image.Type.Sliced; falseToggle.GetComponent <Image>().color = new Color(1f, 1f, 1f, 0.25f); falseToggle.transition = Selectable.Transition.None; falseToggle.isOn = !Value; falseToggle.interactable = !ReadOnly; falseToggle.toggleTransition = Toggle.ToggleTransition.None; falseToggle.graphic = falseSelected; falseToggle.group = toggleGroup; falseToggle.onValueChanged.AddListener((toggled) => { if (toggled) { ValueSetter(false); } }); }
public static void SetTranform(Transform item, UILayerType layer, int layerIndex, Transform parent) { if (parent == null) { return; } string rootName = LayerToString(layer); var root = parent.transform.Find(rootName); if (root == null) { root = new GameObject(rootName).transform; if (parent is RectTransform) { var rectParent = root.gameObject.AddComponent <RectTransform>(); rectParent.anchorMin = Vector2.zero; rectParent.anchorMax = Vector2.one; rectParent.offsetMin = Vector3.zero; rectParent.offsetMax = Vector3.zero; root = rectParent; root.SetParent(parent, false); } else { root.SetParent(parent, true); } if (rootName.StartsWith("-1")) { root.SetAsLastSibling(); } else { int i = 0; for (; i < parent.childCount; i++) { var ritem = parent.GetChild(i); if (ritem.name.StartsWith("-1")) { break; } if (string.Compare(rootName, ritem.name) < 0) { break; } } root.SetSiblingIndex(i); } } item.transform.SetParent(root, !(item.GetComponent <Transform>() is RectTransform)); var childCount = root.childCount; int id = 0; for (int i = 0; i < childCount; i++) { var obj = root.GetChild(i); var panel = obj.GetComponent <IUIPanel>(); if (panel == null || obj == item || panel.UType.layerIndex <= layerIndex) { id = i; } else { break; } } item.SetSiblingIndex(id); }
/// <summary> /// This method creates the containers for the pooling system to use. /// </summary> private void CreatePoolContainers() { SoundsPool = new GameObject().transform; SoundsPool.name = "SoundsPool"; SoundsPool.SetParent(transform); SoundsPlaying = new GameObject().transform; SoundsPlaying.name = "SoundsPlaying"; SoundsPlaying.SetParent(transform); }
// // トップレベルのMonoBehaviourを移植する // public static void CopyVRMComponents(GameObject go, GameObject root, Dictionary <Transform, Transform> map) { { // blendshape var src = go.GetComponent <VRMBlendShapeProxy>(); if (src != null) { var dst = root.AddComponent <VRMBlendShapeProxy>(); dst.BlendShapeAvatar = src.BlendShapeAvatar; } } { var secondary = go.transform.Find("secondary"); if (secondary == null) { secondary = go.transform; } var dstSecondary = root.transform.Find("secondary"); if (dstSecondary == null) { dstSecondary = new GameObject("secondary").transform; dstSecondary.SetParent(root.transform, false); } // 揺れモノ foreach (var src in go.transform.Traverse().Select(x => x.GetComponent <VRMSpringBoneColliderGroup>()).Where(x => x != null)) { var dst = map[src.transform]; var dstColliderGroup = dst.gameObject.AddComponent <VRMSpringBoneColliderGroup>(); dstColliderGroup.Colliders = src.Colliders.Select(y => { var offset = dst.worldToLocalMatrix.MultiplyPoint(src.transform.localToWorldMatrix.MultiplyPoint(y.Offset)); return(new VRMSpringBoneColliderGroup.SphereCollider { Offset = offset, Radius = y.Radius }); }).ToArray(); } foreach (var src in go.transform.Traverse().SelectMany(x => x.GetComponents <VRMSpringBone>())) { var dst = dstSecondary.gameObject.AddComponent <VRMSpringBone>(); dst.m_comment = src.m_comment; dst.RootBones = src.RootBones.Select(x => map[x]).ToList(); if (src.ColliderGroups != null) { dst.ColliderGroups = src.ColliderGroups.Select(x => map[x.transform].GetComponent <VRMSpringBoneColliderGroup>()).ToArray(); } } } { // meta(obsolete) var src = go.GetComponent <VRMMetaInformation>(); if (src != null) { src.CopyTo(root); } } { // meta var src = go.GetComponent <VRMMeta>(); if (src != null) { var dst = root.AddComponent <VRMMeta>(); dst.Meta = src.Meta; } } { // firstPerson var src = go.GetComponent <VRMFirstPerson>(); if (src != null) { src.CopyTo(root, map); } } { // lookAt var src = go.GetComponent <VRMLookAt>(); if (src != null) { src.CopyTo(root, map); } } { // humanoid var dst = root.AddComponent <VRMHumanoidDescription>(); var src = go.GetComponent <VRMHumanoidDescription>(); if (src != null) { dst.Avatar = src.Avatar; dst.Description = src.Description; } else { var animator = go.GetComponent <Animator>(); if (animator != null) { dst.Avatar = animator.avatar; } } } }
private void Reset() { if (_waveContainer == null) { _waveContainer = new GameObject("WaveContainer").transform; _waveContainer.SetParent(transform); _waveContainer.localPosition = Vector3.zero; // Add an initial wave var wave = new GameObject("Wave").transform; wave.SetParent(_waveContainer); wave.localPosition = Vector3.zero; wave.gameObject.AddComponent<WaveProperty>(); } }
protected override void DidActivate(bool firstActivation, ActivationType type) { try { if (firstActivation) { //Largely unchanged from CustomListController. Keep all of this. Instance = this; levelPackTableCellInstance = Resources.FindObjectsOfTypeAll <LevelPackTableCell>().First(x => x.name == "LevelPackTableCell"); levelPackTableCellInstance.reuseIdentifier = ReuseIdentifier; RectTransform container = new GameObject("HorizontalListContainer", typeof(RectTransform)).transform as RectTransform; container.SetParent(rectTransform, false); container.sizeDelta = new Vector2(0, 0); container.anchorMin = new Vector2(0.1f, 0); //Squish the list container a little bit container.anchorMax = new Vector2(0.9f, 1); //To make room for the forward/backward buttons var go = new GameObject("CustomListTableView"); go.SetActive(false); CustomListTableView = go.AddComponent <TableView>(); CustomListTableView.gameObject.AddComponent <RectMask2D>(); CustomListTableView.transform.SetParent(container, false); CustomListTableView.SetPrivateField("_tableType", TableView.TableType.Horizontal); (CustomListTableView.transform as RectTransform).anchorMin = new Vector2(0, 0); (CustomListTableView.transform as RectTransform).anchorMax = new Vector2(1, 1); (CustomListTableView.transform as RectTransform).sizeDelta = new Vector2(0, 0); (CustomListTableView.transform as RectTransform).anchoredPosition = new Vector2(0, 0); CustomListTableView.SetPrivateField("_preallocatedCells", new TableView.CellsGroup[0]); CustomListTableView.SetPrivateField("_isInitialized", false); CustomListTableView.dataSource = this; go.SetActive(true); //Code copied from monkeymanboy's Beat Saber Custom Campaigns mod. Keep these too. PageLeftButton = Instantiate(Resources.FindObjectsOfTypeAll <Button>().Last(x => (x.name == "PageLeftButton")), transform); RectTransform buttonTransform = PageLeftButton.transform.Find("BG") as RectTransform; RectTransform glow = Instantiate(Resources.FindObjectsOfTypeAll <GameObject>().Last(x => (x.name == "GlowContainer")), PageLeftButton.transform).transform as RectTransform; glow.localPosition = buttonTransform.localPosition; glow.anchoredPosition = buttonTransform.anchoredPosition; glow.anchorMin = buttonTransform.anchorMin; glow.anchorMax = buttonTransform.anchorMax; glow.sizeDelta = buttonTransform.sizeDelta; PageLeftButton.transform.localPosition = new Vector3(-80, 2.5f, -5); PageLeftButton.interactable = true; PageLeftButton.onClick.AddListener(() => CustomListTableView.PageScrollUp()); PageRightButton = Instantiate(Resources.FindObjectsOfTypeAll <Button>().Last(x => (x.name == "PageRightButton")), transform); buttonTransform = PageRightButton.transform.Find("BG") as RectTransform; glow = Instantiate(Resources.FindObjectsOfTypeAll <GameObject>().Last(x => (x.name == "GlowContainer")), PageRightButton.transform).transform as RectTransform; glow.localPosition = buttonTransform.localPosition; glow.anchoredPosition = buttonTransform.anchoredPosition; glow.anchorMin = buttonTransform.anchorMin; glow.anchorMax = buttonTransform.anchorMax; glow.sizeDelta = buttonTransform.sizeDelta; PageRightButton.transform.localPosition = new Vector3(80, 2.5f, -5); PageRightButton.interactable = true; PageRightButton.onClick.AddListener(() => CustomListTableView.PageScrollDown()); //Now load my Counter settings and data. The rest from here on out is mainly copied from //the old CountersPlusSettingsViewController, and can be safely removed. foreach (var kvp in AdvancedCounterSettings.counterUIItems) { counterInfos.Add(CreateFromModel(kvp.Key)); } foreach (CustomConfigModel potential in ConfigLoader.LoadCustomCounters()) { counterInfos.Add(new SettingsInfo() { Name = potential.DisplayName, Description = $"A custom counter added by {potential.ModCreator}!", Model = potential, IsCustom = true, }); } //Reload the data, and select the first cell in the list. CustomListTableView.didSelectCellWithIdxEvent += OnCellSelect; CustomListTableView.ReloadData(); CustomListTableView.SelectCellWithIdx(0, false); } } catch (Exception e) { //Edit this with your logging system of choice, or delete it altogether (As this shouldn't really cause Exceptions) Plugin.Log(e.ToString(), Plugin.LogInfo.Error, "Report this as an issue on the Counters+ GitHub."); } }
protected override void DidActivate(bool firstActivation, bool addedToHierarchy, bool screenSystemEnabling) { if (firstActivation) { if (!SongCore.Loader.AreSongsLoaded) { SongCore.Loader.SongsLoadedEvent += SongLoader_SongsLoadedEvent; } Plugin.Log("DidActivate 001"); // get table cell instance _requestListTableCellInstance = Resources.FindObjectsOfTypeAll <LevelListTableCell>().First((LevelListTableCell x) => x.name == "LevelListTableCell"); // initialize Yes/No modal YesNoModal.instance.Setup(); Plugin.Log("DidActivate 002"); _songPreviewPlayer = Resources.FindObjectsOfTypeAll <SongPreviewPlayer>().FirstOrDefault(); RectTransform container = new GameObject("RequestBotContainer", typeof(RectTransform)).transform as RectTransform; container.SetParent(rectTransform, false); #region TableView Setup and Initialization var go = new GameObject("SongRequestTableView", typeof(RectTransform)); go.SetActive(false); go.AddComponent <ScrollRect>(); go.AddComponent <Touchable>(); go.AddComponent <EventSystemListener>(); ScrollView scrollView = go.AddComponent <ScrollView>(); _songListTableView = go.AddComponent <TableView>(); go.AddComponent <RectMask2D>(); _songListTableView.transform.SetParent(container, false); _songListTableView.SetField("_preallocatedCells", new TableView.CellsGroup[0]); _songListTableView.SetField("_isInitialized", false); _songListTableView.SetField("_scrollView", scrollView); var viewport = new GameObject("Viewport").AddComponent <RectTransform>(); viewport.SetParent(go.GetComponent <RectTransform>(), false); go.GetComponent <ScrollRect>().viewport = viewport; (viewport.transform as RectTransform).sizeDelta = new Vector2(70f, 70f); RectTransform content = new GameObject("Content").AddComponent <RectTransform>(); content.SetParent(viewport, false); scrollView.SetField("_contentRectTransform", content); scrollView.SetField("_viewport", viewport); _songListTableView.SetDataSource(this, false); _songListTableView.LazyInit(); go.SetActive(true); (_songListTableView.transform as RectTransform).sizeDelta = new Vector2(70f, 70f); (_songListTableView.transform as RectTransform).anchoredPosition = new Vector2(3f, 0f); _songListTableView.didSelectCellWithIdxEvent += DidSelectRow; _pageUpButton = UIHelper.CreateUIButton("SRMPageUpButton", container, "PracticeButton", new Vector2(0f, 38.5f), new Vector2(15f, 7f), () => { scrollView.PageUpButtonPressed(); }, "˄"); Destroy(_pageUpButton.GetComponentsInChildren <ImageView>().FirstOrDefault(x => x.name == "Underline")); _pageDownButton = UIHelper.CreateUIButton("SRMPageDownButton", container, "PracticeButton", new Vector2(0f, -38.5f), new Vector2(15f, 7f), () => { scrollView.PageDownButtonPressed(); }, "˅"); Destroy(_pageDownButton.GetComponentsInChildren <ImageView>().FirstOrDefault(x => x.name == "Underline")); #endregion CenterKeys = new KEYBOARD(container, "", false, -15, 15); #if UNRELEASED // BUG: Need additional modes disabling one shot buttons // BUG: Need to make sure the buttons are usable on older headsets Plugin.Log("DidActivate 005"); _CurrentSongName = BeatSaberUI.CreateText(container, "", new Vector2(-35, 37f)); _CurrentSongName.fontSize = 3f; _CurrentSongName.color = Color.cyan; _CurrentSongName.alignment = TextAlignmentOptions.Left; _CurrentSongName.enableWordWrapping = false; _CurrentSongName.text = ""; _CurrentSongName2 = BeatSaberUI.CreateText(container, "", new Vector2(-35, 34f)); _CurrentSongName2.fontSize = 3f; _CurrentSongName2.color = Color.cyan; _CurrentSongName2.alignment = TextAlignmentOptions.Left; _CurrentSongName2.enableWordWrapping = false; _CurrentSongName2.text = ""; //CenterKeys.AddKeys(SONGLISTKEY); if (!RequestBot.AddKeyboard(CenterKeys, "mainpanel.kbd")) { CenterKeys.AddKeys(SONGLISTKEY); } ColorDeckButtons(CenterKeys, Color.white, Color.magenta); #endif RequestBot.AddKeyboard(CenterKeys, "CenterPanel.kbd"); CenterKeys.DefaultActions(); #region History button // History button _historyButton = UIHelper.CreateUIButton("SRMHistory", container, "PracticeButton", new Vector2(53f, 30f), new Vector2(25f, 15f), () => { isShowingHistory = !isShowingHistory; RequestBot.SetTitle(isShowingHistory ? "Song Request History" : "Song Request Queue"); if (NumberOfCells() > 0) { _songListTableView.ScrollToCellWithIdx(0, TableView.ScrollPositionType.Beginning, false); _songListTableView.SelectCellWithIdx(0); _selectedRow = 0; } else { _selectedRow = -1; } UpdateRequestUI(true); SetUIInteractivity(); _lastSelection = -1; }, "History"); _historyButton.ToggleWordWrapping(false); _historyHintText = UIHelper.AddHintText(_historyButton.transform as RectTransform, ""); #endregion #region Blacklist button // Blacklist button _blacklistButton = UIHelper.CreateUIButton("SRMBlacklist", container, "PracticeButton", new Vector2(53f, 10f), new Vector2(25f, 15f), () => { if (NumberOfCells() > 0) { void _onConfirm() { RequestBot.Blacklist(_selectedRow, isShowingHistory, true); if (_selectedRow > 0) { _selectedRow--; } confirmDialogActive = false; } // get song var song = SongInfoForRow(_selectedRow).song; // indicate dialog is active confirmDialogActive = true; // show dialog YesNoModal.instance.ShowDialog("Blacklist Song Warning", $"Blacklisting {song["songName"].Value} by {song["authorName"].Value}\r\nDo you want to continue?", _onConfirm, () => { confirmDialogActive = false; }); } }, "Blacklist"); _blacklistButton.ToggleWordWrapping(false); UIHelper.AddHintText(_blacklistButton.transform as RectTransform, "Block the selected request from being queued in the future."); #endregion #region Skip button // Skip button _skipButton = UIHelper.CreateUIButton("SRMSkip", container, "PracticeButton", new Vector2(53f, 0f), new Vector2(25f, 15f), () => { if (NumberOfCells() > 0) { // get song var song = SongInfoForRow(_selectedRow).song; void _onConfirm() { // get selected song currentsong = SongInfoForRow(_selectedRow); // skip it RequestBot.Skip(_selectedRow); // select previous song if not first song if (_selectedRow > 0) { _selectedRow--; } // indicate dialog is no longer active confirmDialogActive = false; } // indicate dialog is active confirmDialogActive = true; // show dialog YesNoModal.instance.ShowDialog("Skip Song Warning", $"Skipping {song["songName"].Value} by {song["authorName"].Value}\r\nDo you want to continue?", _onConfirm, () => { confirmDialogActive = false; }); } }, "Skip"); _skipButton.ToggleWordWrapping(false); UIHelper.AddHintText(_skipButton.transform as RectTransform, "Remove the selected request from the queue."); #endregion #region Play button // Play button _playButton = UIHelper.CreateUIButton("SRMPlay", container, "ActionButton", new Vector2(53f, -10f), new Vector2(25f, 15f), () => { if (NumberOfCells() > 0) { currentsong = SongInfoForRow(_selectedRow); RequestBot.played.Add(currentsong.song); RequestBot.WriteJSON(RequestBot.playedfilename, ref RequestBot.played); SetUIInteractivity(false); RequestBot.Process(_selectedRow, isShowingHistory); _selectedRow = -1; } }, "Play"); _playButton.ToggleWordWrapping(false); _playButton.interactable = ((isShowingHistory && RequestHistory.Songs.Count > 0) || (!isShowingHistory && RequestQueue.Songs.Count > 0)); UIHelper.AddHintText(_playButton.transform as RectTransform, "Download and scroll to the currently selected request."); #endregion #region Queue button // Queue button _queueButton = UIHelper.CreateUIButton("SRMQueue", container, "PracticeButton", new Vector2(53f, -30f), new Vector2(25f, 15f), () => { RequestBotConfig.Instance.RequestQueueOpen = !RequestBotConfig.Instance.RequestQueueOpen; RequestBotConfig.Instance.Save(); RequestBot.WriteQueueStatusToFile(RequestBotConfig.Instance.RequestQueueOpen ? "Queue is open." : "Queue is closed."); RequestBot.Instance.QueueChatMessage(RequestBotConfig.Instance.RequestQueueOpen ? "Queue is open." : "Queue is closed."); UpdateRequestUI(); }, RequestBotConfig.Instance.RequestQueueOpen ? "Queue Open" : "Queue Closed"); _queueButton.ToggleWordWrapping(true); _queueButton.SetButtonUnderlineColor(RequestBotConfig.Instance.RequestQueueOpen ? Color.green : Color.red); _queueButton.SetButtonTextSize(3.5f); UIHelper.AddHintText(_queueButton.transform as RectTransform, "Open/Close the queue."); #endregion // Set default RequestFlowCoordinator title RequestBot.SetTitle(isShowingHistory ? "Song Request History" : "Song Request Queue"); } base.DidActivate(firstActivation, addedToHierarchy, screenSystemEnabling); if (addedToHierarchy) { _selectedRow = -1; _songListTableView.ClearSelection(); } UpdateRequestUI(); SetUIInteractivity(true); }
public virtual void init() { // [ cliear ] this.clear(); // [ RectTransform ] var rectTransform = this.GetComponent <RectTransform>(); rectTransform.setFullSize(); // [ ScrollRect ] var scrollRect = this.GetComponent <ScrollRect>(); scrollRect.horizontal = this.direction == Direction.Horizontal; scrollRect.vertical = this.direction == Direction.Vertical; scrollRect.scrollSensitivity = 15f; // [ ScrollRect / Viewport ] var viewportRect = new GameObject("Viewport", typeof(RectTransform), typeof(Mask), typeof(Image)).GetComponent <RectTransform>(); viewportRect.SetParent(scrollRect.transform, false); viewportRect.setFullSize(); viewportRect.offsetMin = new Vector2(10f, 10f); viewportRect.offsetMax = new Vector2(-10f, -10f); var viewportImage = viewportRect.GetComponent <Image>(); //viewportImage.sprite = UnityEditor.AssetDatabase.GetBuiltinExtraResource<Sprite>("UI/Skin/UIMask.psd"); viewportImage.type = Image.Type.Sliced; var viewportMask = viewportRect.GetComponent <Mask>(); viewportMask.showMaskGraphic = false; scrollRect.viewport = viewportRect; // [ ScrollRect / Viewport / Content ] var contentRect = new GameObject("Content", typeof(RectTransform)).GetComponent <RectTransform>(); contentRect.SetParent(viewportRect, false); if (this.direction == Direction.Horizontal) { contentRect.setSizeFromLeft(1.0f); } else { contentRect.setSizeFromTop(1.0f); } var contentRectSize = contentRect.getSize(); contentRect.setSize(contentRectSize - contentRectSize * 0.06f); scrollRect.content = contentRect; // [ ScrollRect / Viewport / Content / PrototypeItem ] this.resetPrototypeItem(contentRect); // [ ScrollRect / Scrollbar ] var scrollbarName = this.direction == Direction.Horizontal ? "Scrollbar Horizontal" : "Scrollbar Vertical"; var scrollbarRect = new GameObject(scrollbarName, typeof(Scrollbar), typeof(Image)).GetComponent <RectTransform>(); scrollbarRect.SetParent(viewportRect, false); if (this.direction == Direction.Horizontal) { scrollbarRect.setSizeFromBottom(0.05f); } else { scrollbarRect.setSizeFromRight(0.05f); } scrollbarRect.SetParent(scrollRect.transform, true); var scrollbar = scrollbarRect.GetComponent <Scrollbar>(); scrollbar.direction = (this.direction == Direction.Horizontal) ? Scrollbar.Direction.LeftToRight : Scrollbar.Direction.BottomToTop; if (this.direction == Direction.Horizontal) { scrollRect.horizontalScrollbar = scrollbar; } else { scrollRect.verticalScrollbar = scrollbar; } // [ ScrollRect / Scrollbar / Image ] var scrollbarImage = scrollbarRect.GetComponent <Image>(); #if UNITY_EDITOR scrollbarImage.sprite = UnityEditor.AssetDatabase.GetBuiltinExtraResource <Sprite>("UI/Skin/Background.psd"); #endif scrollbarImage.color = new Color(0.1f, 0.1f, 0.1f, 0.5f); scrollbarImage.type = Image.Type.Sliced; // [ ScrollRect / Scrollbar / slidingArea ] var slidingAreaRect = new GameObject("Sliding Area", typeof(RectTransform)).GetComponent <RectTransform>(); slidingAreaRect.SetParent(scrollbarRect, false); slidingAreaRect.setFullSize(); // [ ScrollRect / Scrollbar / slidingArea / Handle ] var scrollbarHandleRect = new GameObject("Handle", typeof(Image)).GetComponent <RectTransform>(); scrollbarHandleRect.SetParent(slidingAreaRect, false); scrollbarHandleRect.setFullSize(); var scrollbarHandleImage = scrollbarHandleRect.GetComponent <Image>(); #if UNITY_EDITOR scrollbarHandleImage.sprite = UnityEditor.AssetDatabase.GetBuiltinExtraResource <Sprite>("UI/Skin/UISprite.psd"); #endif scrollbarHandleImage.color = new Color(0.5f, 0.5f, 1.0f, 0.5f); scrollbarHandleImage.type = Image.Type.Sliced; scrollbar.handleRect = scrollbarHandleRect; // [ ScrollRect / ScrollbarHandleSize ] var scrollbarHandleSize = scrollRect.GetComponent <ScrollbarHandleSize>(); if (scrollbarHandleSize == null) { scrollbarHandleSize = scrollRect.gameObject.AddComponent <ScrollbarHandleSize>(); scrollbarHandleSize.maxSize = 1.0f; scrollbarHandleSize.minSize = 0.1f; } // [ Layer ] this.gameObject.setLayer(this.transform.parent.gameObject.layer, true); }
public virtual void AdjustBoatAndDummyBoatBlockPositions() { if ((boatDummyBlockEntityData != null && boatDummyBlockEntityData.bHasTransform)) { DebugMsg("AdjustBoatAndDummyBoatBlockPositions: Found Boat BlockEntityData: positioning Dummy Boat Mesh"); // Offset the dummy boat block mesh to the Y position of the boat vehicle Vector3 boatDummyPosVec3 = boatDummyPos.ToVector3(); DebugMsg("AdjustBoatAndDummyBoatBlockPositions: before Offset: boatDummyPos = " + boatDummyPosVec3.ToString("0.000") + " | boat dummy transform pos = " + boatDummyBlockEntityData.transform.position.ToString("0.000") + " | boat vehicle pos = " + this.transform.position.ToString("0.000")); boatDummyPosVec3 = boatDummyBlockEntityData.transform.position; if (bNeedLoadAdjustments) { boatDummyPosVec3.y = boatDummyPos_YOffset; } else { //boatDummyPosVec3.y = this.transform.position.y; boatDummyPosVec3.y += 0.3f; // In MP the current boat position is flaky, so I'm harcoding it for now. } boatDummyPos = boatDummyBlockEntityData.pos; // for persistence boatDummyBlockEntityData.transform.position = boatDummyPosVec3; boatDummyPos_YOffset = boatDummyPosVec3.y; // for persistence // Snap the boat vehicle to the boat dummy block XZ position Transform tmpOffsetTransform = new GameObject("tmp").transform; tmpOffsetTransform.SetParent(boatDummyBlockEntityData.transform); tmpOffsetTransform.localRotation = Quaternion.identity; tmpOffsetTransform.localPosition = new Vector3(-0.5f, 0, -0.5f); this.transform.position = tmpOffsetTransform.position; this.SetPosition(tmpOffsetTransform.position); if (player != null && !bNeedLoadAdjustments && !bSpawningBoatChassis && hasPlayerExitPos) { Vector3 exitPos = tmpOffsetTransform.position + playerExitPos; player.transform.position = exitPos; player.SetPosition(exitPos); } bSpawningBoatChassis = false; if (tmpOffsetTransform != null) { Destroy(tmpOffsetTransform.gameObject); } // Hide the dummy boat block mesh MeshRenderer[] meshRenderers = boatDummyBlockEntityData.transform.gameObject.GetComponentsInChildren <MeshRenderer>(true); foreach (MeshRenderer mr in meshRenderers) { mr.enabled = false; } bNeedBoatDummyBlockOffset = false; failedAdjustBoatPosCount = 0; if (bNeedLoadAdjustments) { DebugMsg("AdjustBoatAndDummyBoatBlockPositions: Load Adjustments Done."); bNeedLoadAdjustments = false; } } else { if (boatDummyBlockEntityData != null) { DebugMsg("AdjustBoatAndDummyBoatBlockPositions: Boat BlockEntityData does not have a transform"); } else if (boatDummyBlockEntityData == null) { DebugMsg("AdjustBoatAndDummyBoatBlockPositions: Boat BlockEntityData is NULL."); } else { DebugMsg("AdjustBoatAndDummyBoatBlockPositions: boatDummyBlockTransform is NULL."); } } }
public IEnumerator ContactInteractorTargetStaysValidWhenTouchingAnyCollider([ValueSource(nameof(s_ContactInteractors))] Type interactorType) { // This tests that an Interactable will stay as a valid target as long as // the Direct and Socket Interactor is touching any Collider associated with the Interactable, // and remains so if only some (but not all) of the Interactable colliders leaves. var manager = TestUtilities.CreateInteractionManager(); XRBaseInteractor interactor = null; if (interactorType == typeof(XRDirectInteractor)) { interactor = TestUtilities.CreateDirectInteractor(); } else if (interactorType == typeof(XRSocketInteractor)) { interactor = TestUtilities.CreateSocketInteractor(); } Assert.That(interactor, Is.Not.Null); var triggerCollider = interactor.GetComponent <SphereCollider>(); Assert.That(triggerCollider, Is.Not.Null); Assert.That(triggerCollider.isTrigger, Is.True); var interactable = TestUtilities.CreateGrabInteractable(); // Prevent the Interactable from being selected to allow the object to be moved freely interactable.interactionLayerMask = 0; var sphereCollider = interactable.GetComponent <SphereCollider>(); sphereCollider.center = Vector3.zero; sphereCollider.radius = 0.5f; Assert.That(sphereCollider, Is.Not.Null); interactable.transform.position = Vector3.forward * 10f; // Create another Collider to have as part of the Interactable var boxColliderTransform = new GameObject("Box Collider", typeof(BoxCollider)).transform; boxColliderTransform.SetParent(interactable.transform); boxColliderTransform.localPosition = Vector3.right; boxColliderTransform.localRotation = Quaternion.identity; var boxCollider = boxColliderTransform.GetComponent <BoxCollider>(); boxCollider.center = Vector3.zero; boxCollider.size = Vector3.one; interactable.colliders.Clear(); interactable.colliders.Add(sphereCollider); interactable.colliders.Add(boxCollider); interactable.enabled = false; interactable.enabled = true; Assert.That(manager.GetInteractableForCollider(sphereCollider), Is.EqualTo(interactable)); Assert.That(manager.GetInteractableForCollider(boxCollider), Is.EqualTo(interactable)); yield return(null); yield return(new WaitForFixedUpdate()); var directOverlaps = Physics.OverlapSphere(triggerCollider.transform.position, triggerCollider.radius, -1, QueryTriggerInteraction.Ignore); Assert.That(directOverlaps, Is.Empty); var validTargets = new List <XRBaseInteractable>(); interactor.GetValidTargets(validTargets); Assert.That(validTargets, Is.Empty); // Move the Interactable to the Direct Interactor so that it overlaps both colliders interactable.transform.position = Vector3.left * 0.5f; yield return(new WaitForFixedUpdate()); yield return(null); directOverlaps = Physics.OverlapSphere(triggerCollider.transform.position, triggerCollider.radius, -1, QueryTriggerInteraction.Ignore); Assert.That(directOverlaps, Is.EquivalentTo(new Collider[] { sphereCollider, boxCollider })); interactor.GetValidTargets(validTargets); Assert.That(validTargets, Is.EqualTo(new[] { interactable })); // Move the Interactable some so one of the colliders leaves interactable.transform.position = Vector3.left * 2f; yield return(new WaitForFixedUpdate()); yield return(null); directOverlaps = Physics.OverlapSphere(triggerCollider.transform.position, triggerCollider.radius, -1, QueryTriggerInteraction.Ignore); Assert.That(directOverlaps, Is.EquivalentTo(new Collider[] { boxCollider })); interactor.GetValidTargets(validTargets); Assert.That(validTargets, Is.EqualTo(new[] { interactable })); // Move the Interactable some so the other collider is the one being hovered // to test that colliders can re-enter after previously exiting interactable.transform.position = Vector3.right * 1f; yield return(new WaitForFixedUpdate()); yield return(null); directOverlaps = Physics.OverlapSphere(triggerCollider.transform.position, triggerCollider.radius, -1, QueryTriggerInteraction.Ignore); Assert.That(directOverlaps, Is.EquivalentTo(new Collider[] { sphereCollider })); interactor.GetValidTargets(validTargets); Assert.That(validTargets, Is.EqualTo(new[] { interactable })); // Move the Interactable so all colliders exits the Direct Interactor interactable.transform.position = Vector3.forward * 10f; yield return(new WaitForFixedUpdate()); yield return(null); directOverlaps = Physics.OverlapSphere(triggerCollider.transform.position, triggerCollider.radius, -1, QueryTriggerInteraction.Ignore); Assert.That(directOverlaps, Is.Empty); interactor.GetValidTargets(validTargets); Assert.That(validTargets, Is.Empty); }
private GameObject CreateFromData(URDFData data) { Transform actor = new GameObject(data.Name).transform; actor.position = new Vector3(0f, 0f, 0f); actor.rotation = Quaternion.identity; List <Transform> Links = new List <Transform>(); List <Transform> Joints = new List <Transform>(); //Create Link Transforms for (int i = 0; i < data.Links.Count; i++) { Transform link = CreateGeometry(data.Links[i].Geometry).transform; link.name = data.Links[i].Name; link.SetParent(actor, false); Links.Add(link); } //Create Joint Transforms for (int i = 0; i < data.Joints.Count; i++) { Transform joint = new GameObject().transform; joint.name = data.Joints[i].Name; joint.SetParent(actor); Joints.Add(joint); } //Apply Parent-Child Relations for (int i = 0; i < Joints.Count; i++) { Transform joint = Joints[i]; Transform parent = FindTransformByName(Links, data.GetJointData(joint.name).Parent); Transform child = FindTransformByName(Links, data.GetJointData(joint.name).Child); Transform parentJoint = actor; string parentName = data.GetLinkData(parent.name).Name; for (int j = 0; j < Joints.Count; j++) { if (data.GetJointData(Joints[j].name).Child == parentName) { parentJoint = Joints[j]; break; } } joint.SetParent(parentJoint); child.SetParent(joint); } Links = GetOrderedTransforms(actor.root, Links, new List <Transform>()); Joints = GetOrderedTransforms(actor.root, Joints, new List <Transform>()); for (int i = 0; i < Joints.Count; i++) { Transform joint = Joints[i]; Vector3 angles = -Mathf.Rad2Deg * ROSToUnity(data.GetJointData(joint.name).OriginRPY); Quaternion rotation = Quaternion.Euler(angles); joint.position = joint.parent.position + joint.parent.rotation * ROSToUnity(data.GetJointData(joint.name).OriginXYZ); joint.rotation = joint.parent.rotation * rotation; } for (int i = 0; i < Links.Count; i++) { Transform link = Links[i]; Vector3 angles = -Mathf.Rad2Deg * ROSToUnity(data.GetLinkData(link.name).RPY); Quaternion rotation = Quaternion.Euler(angles); link.localPosition += ROSToUnity(data.GetLinkData(link.name).XYZ); link.localRotation = rotation * link.localRotation; } //Initialize Links for (int i = 0; i < Links.Count; i++) { //Nothing to do. } //Initialize Joints for (int i = 0; i < Joints.Count; i++) { BioIK.KinematicJoint joint = Joints[i].gameObject.AddComponent <BioIK.KinematicJoint>(); URDFData.JointData jointData = data.GetJointData(joint.name); if (jointData.Type == "fixed") { //Nothing to do } else { switch (jointData.Type) { case "prismatic": joint.SetJointType(BioIK.JointType.Prismatic); break; case "revolute": joint.SetJointType(BioIK.JointType.Revolute); break; case "continuous": joint.SetJointType(BioIK.JointType.Continuous); break; } joint.SetAnchor(Vector3.zero); Vector3 axis = ROSToUnity(jointData.Axis); if (joint.GetJointType() != BioIK.JointType.Prismatic) { axis = -axis; } joint.SetOrientation(Quaternion.FromToRotation(Vector3.right, axis).eulerAngles); //joint.SetMaximumVelocity(jointData.Velocity); //joint.SetMaximumAcceleration(jointData.Velocity); BioIK.Motion motion = joint.GetXMotion(); motion.SetEnabled(true); motion.SetLowerLimit(jointData.LowerLimit); motion.SetUpperLimit(jointData.UpperLimit); joint.Initialise(); } } if (Errors == 0) { Debug.Log("Successfully imported '" + actor.name + "'."); } else { Debug.Log(Errors + " errors or warnings during importing '" + actor.name + "'.\n" + Output); } Output = string.Empty; Errors = 0; return(actor.gameObject); }
public void GenerateMap() { currentMap = maps[mapIndex]; tileMap = new Transform[currentMap.mapSize.x, currentMap.mapSize.y]; System.Random prng = new System.Random(currentMap.seed); // Generating coords allTilesCoords = new List <Coord>(); for (int x = 0; x < currentMap.mapSize.x; x++) { for (int y = 0; y < currentMap.mapSize.y; y++) { allTilesCoords.Add(new Coord(x, y)); } } shuffledTileCoords = new Queue <Coord>(Utility.ShuffleArray <Coord>(allTilesCoords.ToArray(), currentMap.seed)); // Create map holder obj string holderName = "Generated Map"; if (transform.Find(holderName)) { DestroyImmediate(transform.Find(holderName).gameObject); } Transform mapHolder = new GameObject(holderName).transform; mapHolder.SetParent(transform); // Spawning tiles for (int x = 0; x < currentMap.mapSize.x; x++) { for (int y = 0; y < currentMap.mapSize.y; y++) { Vector3 tilePosition = CoordToPosition(x, y); Transform newTile = Instantiate <Transform>(tilePrefab, tilePosition, Quaternion.Euler(Vector3.right * 90)); newTile.SetParent(mapHolder); newTile.localScale = Vector3.one * (1 - outlinePercent) * tileSize; tileMap[x, y] = newTile.transform; } } // Spawing obstacles bool[,] obstacleMap = new bool[(int)currentMap.mapSize.x, (int)currentMap.mapSize.y]; int obstacleCount = (int)(currentMap.mapSize.x * currentMap.mapSize.y * currentMap.obstaclePercent); int currentObstacleCount = 0; List <Coord> allOpenCoords = new List <Coord>(allTilesCoords); for (int i = 0; i < obstacleCount; i++) { Coord randomCoord = GetRandomCoord(); obstacleMap[randomCoord.x, randomCoord.y] = true; currentObstacleCount++; if (randomCoord != currentMap.mapCentre && MapIsFullyAccessible(obstacleMap, currentObstacleCount)) { float obstacleHeight = Mathf.Lerp(currentMap.minObstacleHeight, currentMap.maxObstacleHeight, (float)prng.NextDouble()); Vector3 obstaclePosition = CoordToPosition(randomCoord.x, randomCoord.y); Transform newObstacle = Instantiate <Transform>(obstaclePrefab, obstaclePosition + Vector3.up * obstacleHeight / 2f, Quaternion.identity); newObstacle.SetParent(mapHolder); newObstacle.localScale = new Vector3((1 - outlinePercent) * tileSize, obstacleHeight, (1 - outlinePercent) * tileSize); Renderer obstacleRenderer = newObstacle.GetComponent <Renderer>(); Material obstacleMaterial = new Material(obstacleRenderer.sharedMaterial); float colorPercent = randomCoord.y / (float)currentMap.mapSize.y; obstacleMaterial.color = Color.Lerp(currentMap.foregroundColor, currentMap.backgroundColor, colorPercent); obstacleRenderer.sharedMaterial = obstacleMaterial; allOpenCoords.Remove(randomCoord); } else { obstacleMap[randomCoord.x, randomCoord.y] = false; currentObstacleCount--; } } shuffledOpenTileCoords = new Queue <Coord>(Utility.ShuffleArray <Coord>(allOpenCoords.ToArray(), currentMap.seed)); mapFloor.localScale = new Vector3(currentMap.mapSize.x * tileSize, currentMap.mapSize.y * tileSize); navMeshFloor.localScale = new Vector3(maxMapSize.x, maxMapSize.y) * tileSize; if (navMeshSurface == null) { navMeshSurface = GetComponent <NavMeshSurface>(); } navMeshSurface.BuildNavMesh(); }
protected override void DidActivate(bool firstActivation, ActivationType type) { if (firstActivation && type == ActivationType.AddedToHierarchy) { _beatmapCharacteristics = Resources.FindObjectsOfTypeAll <BeatmapCharacteristicSO>(); _songTableCellInstance = Resources.FindObjectsOfTypeAll <LevelListTableCell>().First(x => (x.name == "LevelListTableCell")); _searchButton = this.CreateUIButton("CreditsButton", new Vector2(-20f, 36.25f), new Vector2(20f, 6f), () => { SearchPressed?.Invoke(); }, "Search"); _searchButton.SetButtonTextSize(3f); _searchButton.ToggleWordWrapping(false); _sortByButton = this.CreateUIButton("CreditsButton", new Vector2(0f, 36.25f), new Vector2(20f, 6f), () => { SelectTopButtons(TopButtonsState.SortBy); }, "Sort By"); _sortByButton.SetButtonTextSize(3f); _sortByButton.ToggleWordWrapping(false); _modeButton = this.CreateUIButton("CreditsButton", new Vector2(20f, 36.25f), new Vector2(20f, 6f), () => { SelectTopButtons(TopButtonsState.Mode); }, "Mode"); _modeButton.SetButtonTextSize(3f); _modeButton.ToggleWordWrapping(false); _defButton = this.CreateUIButton("CreditsButton", new Vector2(-20f, 36.25f), new Vector2(20f, 6f), () => { SelectTopButtons(TopButtonsState.Select); SortPressed?.Invoke(SortMode.Default); }, "Default"); _defButton.SetButtonTextSize(3f); _defButton.ToggleWordWrapping(false); _defButton.gameObject.SetActive(false); _newButton = this.CreateUIButton("CreditsButton", new Vector2(0f, 36.25f), new Vector2(20f, 6f), () => { SelectTopButtons(TopButtonsState.Select); SortPressed?.Invoke(SortMode.Newest); }, "Newest"); _newButton.SetButtonTextSize(3f); _newButton.ToggleWordWrapping(false); _newButton.gameObject.SetActive(false); _diffButton = this.CreateUIButton("CreditsButton", new Vector2(20f, 36.25f), new Vector2(20f, 6f), () => { SelectTopButtons(TopButtonsState.Select); SortPressed?.Invoke(SortMode.Difficulty); }, "Difficulty"); _diffButton.SetButtonTextSize(3f); _diffButton.ToggleWordWrapping(false); _diffButton.gameObject.SetActive(false); _stdButton = this.CreateUIButton("CreditsButton", new Vector2(-20f, 36.25f), new Vector2(20f, 6f), () => { SelectTopButtons(TopButtonsState.Select); ModePressed?.Invoke(_beatmapCharacteristics.First(x => x.characteristicName == "Standard")); }, "Standard"); _stdButton.SetButtonTextSize(3f); _stdButton.ToggleWordWrapping(false); _stdButton.gameObject.SetActive(false); _oneSbrButton = this.CreateUIButton("CreditsButton", new Vector2(0f, 36.25f), new Vector2(20f, 6f), () => { SelectTopButtons(TopButtonsState.Select); ModePressed?.Invoke(_beatmapCharacteristics.First(x => x.characteristicName == "One Saber")); }, "One Saber"); _oneSbrButton.SetButtonTextSize(3f); _oneSbrButton.ToggleWordWrapping(false); _oneSbrButton.gameObject.SetActive(false); _noArrButton = this.CreateUIButton("CreditsButton", new Vector2(20f, 36.25f), new Vector2(20f, 6f), () => { SelectTopButtons(TopButtonsState.Select); ModePressed?.Invoke(_beatmapCharacteristics.First(x => x.characteristicName == "No Arrows")); }, "No Arrows"); _noArrButton.SetButtonTextSize(3f); _noArrButton.ToggleWordWrapping(false); _noArrButton.gameObject.SetActive(false); _pageUpButton = Instantiate(Resources.FindObjectsOfTypeAll <Button>().First(x => (x.name == "PageUpButton")), rectTransform, false); (_pageUpButton.transform as RectTransform).anchorMin = new Vector2(0.5f, 1f); (_pageUpButton.transform as RectTransform).anchorMax = new Vector2(0.5f, 1f); (_pageUpButton.transform as RectTransform).anchoredPosition = new Vector2(0f, -12f); (_pageUpButton.transform as RectTransform).sizeDelta = new Vector2(40f, 6f); _pageUpButton.interactable = true; _pageUpButton.onClick.AddListener(delegate() { _songsTableView.PageScrollUp(); }); _pageUpButton.interactable = false; _pageDownButton = Instantiate(Resources.FindObjectsOfTypeAll <Button>().First(x => (x.name == "PageDownButton")), rectTransform, false); (_pageDownButton.transform as RectTransform).anchorMin = new Vector2(0.5f, 0f); (_pageDownButton.transform as RectTransform).anchorMax = new Vector2(0.5f, 0f); (_pageDownButton.transform as RectTransform).anchoredPosition = new Vector2(0f, 6f); (_pageDownButton.transform as RectTransform).sizeDelta = new Vector2(40f, 6f); _pageDownButton.interactable = true; _pageDownButton.onClick.AddListener(delegate() { _songsTableView.PageScrollDown(); }); _pageDownButton.interactable = false; RectTransform container = new GameObject("Content", typeof(RectTransform)).transform as RectTransform; container.SetParent(rectTransform, false); container.anchorMin = new Vector2(0.3f, 0.5f); container.anchorMax = new Vector2(0.7f, 0.5f); container.sizeDelta = new Vector2(0f, 60f); container.anchoredPosition = new Vector2(0f, -3f); _songsTableView = new GameObject("CustomTableView").AddComponent <TableView>(); _songsTableView.gameObject.AddComponent <RectMask2D>(); _songsTableView.transform.SetParent(container, false); _songsTableView.SetPrivateField("_isInitialized", false); _songsTableView.SetPrivateField("_preallocatedCells", new TableView.CellsGroup[0]); _songsTableView.Init(); (_songsTableView.transform as RectTransform).anchorMin = new Vector2(0f, 0f); (_songsTableView.transform as RectTransform).anchorMax = new Vector2(1f, 1f); (_songsTableView.transform as RectTransform).sizeDelta = new Vector2(0f, 0f); (_songsTableView.transform as RectTransform).anchoredPosition = new Vector3(0f, 0f); ReflectionUtil.SetPrivateField(_songsTableView, "_pageUpButton", _pageUpButton); ReflectionUtil.SetPrivateField(_songsTableView, "_pageDownButton", _pageDownButton); _songsTableView.didSelectRowEvent += SongsTableView_DidSelectRow; _songsTableView.dataSource = this; _hostIsSelectingSongText = BeatSaberUI.CreateText(rectTransform, "Host is selecting song...", new Vector2(0f, 0f)); _hostIsSelectingSongText.fontSize = 8f; _hostIsSelectingSongText.alignment = TextAlignmentOptions.Center; _hostIsSelectingSongText.rectTransform.sizeDelta = new Vector2(120f, 6f); SelectTopButtons(TopButtonsState.Select); } else { _songsTableView.ReloadData(); } }
private void TryBuild(Entity entity, GameObject prefab, GameObject instance, string directory, string prefabPath, IDictionary <int, IDictionary <int, Sprite> > folders) { var controllerPath = string.Format("{0}/{1}.controller", directory, entity.name); var animator = instance.GetComponent <Animator> (); //Fetches the prefab's Animator if (animator == null) { animator = instance.AddComponent <Animator> (); //Or creates one if it doesn't exist } AnimatorController controller = null; if (animator.runtimeAnimatorController != null) //The controller we use is hopefully the controller attached to the animator { controller = animator.runtimeAnimatorController as AnimatorController ?? //Or the one that's referenced by an OverrideController (AnimatorController)((AnimatorOverrideController)animator.runtimeAnimatorController).runtimeAnimatorController; } if (controller == null) //Otherwise we have to check the AssetDatabase for our controller { controller = (AnimatorController)AssetDatabase.LoadAssetAtPath(controllerPath, typeof(AnimatorController)); if (controller == null) { controller = AnimatorController.CreateAnimatorControllerAtPath(controllerPath); //Or create a new one if it doesn't exist. ProcessingInfo.NewControllers.Add(controller); } animator.runtimeAnimatorController = controller; } var transforms = new Dictionary <string, Transform> (); //All of the bones and sprites, identified by TimeLine.name, because those are truly unique transforms ["rootTransform"] = instance.transform; //The root GameObject needs to be part of this hierarchy as well var defaultBones = new Dictionary <string, SpatialInfo> (); //These are basically the object states on the first frame of the first animation var defaultSprites = new Dictionary <string, SpriteInfo> (); //They are used as control values in determining whether something has changed var animBuilder = new AnimationBuilder(ProcessingInfo, folders, transforms, defaultBones, defaultSprites, prefabPath, controller); var firstAnim = true; //The prefab's graphic will be determined by the first frame of the first animation foreach (var animation in entity.animations) { var timeLines = new Dictionary <int, TimeLine> (); foreach (var timeLine in animation.timelines) //TimeLines hold all the critical data such as positioning and graphics used { timeLines [timeLine.id] = timeLine; } foreach (var key in animation.mainlineKeys) { var parents = new Dictionary <int, string> (); //Parents are referenced by different IDs V_V parents [-1] = "rootTransform"; //This is where "-1 == no parent" comes in handy var boneRefs = new Queue <Ref> (key.boneRefs ?? new Ref[0]); while (boneRefs.Count > 0) { var bone = boneRefs.Dequeue(); var timeLine = timeLines [bone.timeline]; parents [bone.id] = timeLine.name; if (!transforms.ContainsKey(timeLine.name)) //We only need to go through this once, so ignore it if it's already in the dict { if (parents.ContainsKey(bone.parent)) //If the parent cannot be found, it will probably be found later, so save it { var parentID = parents [bone.parent]; var parent = transforms [parentID]; var child = parent.Find(timeLine.name); //Try to find the child transform if it exists if (child == null) //Or create a new one { child = new GameObject(timeLine.name).transform; child.SetParent(parent); } transforms [timeLine.name] = child; var spatialInfo = defaultBones [timeLine.name] = ArrayUtility.Find(timeLine.keys, x => x.id == bone.key).info; if (!spatialInfo.processed) { SpatialInfo parentInfo; defaultBones.TryGetValue(parentID, out parentInfo); spatialInfo.Process(parentInfo); } child.localPosition = new Vector3(spatialInfo.x, spatialInfo.y, 0f); child.localRotation = spatialInfo.rotation; child.localScale = new Vector3(spatialInfo.scale_x, spatialInfo.scale_y, 1f); } else { boneRefs.Enqueue(bone); } } } foreach (var oref in key.objectRefs) { var timeLine = timeLines [oref.timeline]; if (!transforms.ContainsKey(timeLine.name)) //Same as above { var parentID = parents [oref.parent]; var parent = transforms [parentID]; var child = parent.Find(timeLine.name); if (child == null) { child = new GameObject(timeLine.name).transform; child.SetParent(parent); } transforms [timeLine.name] = child; var swapper = child.GetComponent <TextureController> (); //Destroy the Sprite Swapper, we'll make a new one later if (swapper != null) { DestroyImmediate(swapper); } var renderer = child.GetComponent <SpriteRenderer> (); //Get or create a Sprite Renderer if (renderer == null) { renderer = child.gameObject.AddComponent <SpriteRenderer> (); } var spriteInfo = defaultSprites [timeLine.name] = (SpriteInfo)ArrayUtility.Find(timeLine.keys, x => x.id == 0).info; renderer.sprite = folders [spriteInfo.folder] [spriteInfo.file]; if (!spriteInfo.processed) { SpatialInfo parentInfo; defaultBones.TryGetValue(parentID, out parentInfo); spriteInfo.Process(parentInfo); } child.localPosition = new Vector3(spriteInfo.x, spriteInfo.y, oref.z_index); //Z-index helps determine draw order child.localEulerAngles = new Vector3(0f, 0f, spriteInfo.angle); //The reason I don't use layers or layer orders is because child.localScale = new Vector3(spriteInfo.scale_x, spriteInfo.scale_y, 1f); //There tend to be a LOT of body parts, it's better to treat var color = renderer.color; //The entity as a single sprite for layer sorting purposes. color.a = spriteInfo.a; renderer.color = color; if (!firstAnim) { child.gameObject.SetActive(false); //Disable the GameObject if this isn't the first frame of the first animation } } } if (firstAnim) { firstAnim = false; } } try { animBuilder.Build(animation, timeLines); //Builds the currently processed AnimationClip, see AnimationBuilder for more info } catch (Exception e) { Debug.LogErrorFormat("Unable to build animation '{0}' for '{1}', reason: {2}", animation.name, entity.name, e); } } if (instance.GetComponent <EntityRenderer> () == null) { instance.AddComponent <EntityRenderer> (); //Adds an EntityRenderer if one is not already present } PrefabUtility.ReplacePrefab(instance, prefab, ReplacePrefabOptions.ConnectToPrefab); DestroyImmediate(instance); //Apply the instance's changes to the prefab, then destroy the instance. }
public static Transform CheckForIndividualFiltersAndSkins(GameObject gameObjectToCheck, int menuButtonIndex = -1, bool isNetworked = true) { bool hasMeshFilter = false; MeshFilter filter = default; bool hasSkinnedRenderer = false; SkinnedMeshRenderer skinnedRenderer = default; //Access what components are available filter = gameObjectToCheck.GetComponent <MeshFilter>(); if (filter != null) { hasMeshFilter = true; } skinnedRenderer = gameObjectToCheck.GetComponent <SkinnedMeshRenderer>(); if (skinnedRenderer != null) { hasSkinnedRenderer = true; } var animationComponent = gameObjectToCheck.GetComponent <Animation>(); if (animationComponent) { animationComponent.animatePhysics = true; } //to avoid selecting different anim references between checking if (hasMeshFilter || hasSkinnedRenderer) { // create new parent to be a pivot of object to deform correctly when grabbing Transform newParent = new GameObject().transform; //set new parent with sibling pos and scale newParent.SetParent(gameObjectToCheck.transform.parent, true); newParent.localPosition = gameObjectToCheck.transform.localPosition; newParent.localScale = gameObjectToCheck.transform.localScale; if (hasMeshFilter) { //set the parent as a child to set pivot in correct location newParent.SetParent(gameObjectToCheck.transform, true); newParent.transform.localRotation = Quaternion.identity; //set grab tag newParent.gameObject.tag = TagList.interactable; BoxCollider tempCollider = newParent.gameObject.AddComponent <BoxCollider>(); tempCollider.size = filter.mesh.bounds.size; newParent.localPosition = filter.mesh.bounds.center; if (isNetworked) { NetworkedObjectsManager.Instance.CreateNetworkedGameObject(newParent.gameObject, menuButtonIndex); } } else if (hasSkinnedRenderer) // NOTE(david): animated objects are considered to have skinned mesh renderers and given whole collider { //set anim objects as one whole object if (skinnedRenderer.rootBone) { } } return(newParent); } return(null); }
/// <summary> /// VRMを構成するコンポーネントをコピーする。 /// </summary> /// <param name="go">コピー元</param> /// <param name="root">コピー先</param> /// <param name="map">コピー元とコピー先の対応関係</param> static void CopyVRMComponents(GameObject go, GameObject root, Dictionary <Transform, Transform> map) { { // blendshape var src = go.GetComponent <VRMBlendShapeProxy>(); if (src != null) { var dst = root.AddComponent <VRMBlendShapeProxy>(); dst.BlendShapeAvatar = src.BlendShapeAvatar; } } { var secondary = go.transform.Find("secondary"); if (secondary == null) { secondary = go.transform; } var dstSecondary = root.transform.Find("secondary"); if (dstSecondary == null) { dstSecondary = new GameObject("secondary").transform; dstSecondary.SetParent(root.transform, false); } // 揺れモノ foreach (var src in go.transform.GetComponentsInChildren <VRMSpringBoneColliderGroup>()) { var dst = map[src.transform]; var dstColliderGroup = dst.gameObject.AddComponent <VRMSpringBoneColliderGroup>(); dstColliderGroup.Colliders = src.Colliders.Select(y => { var offset = dst.worldToLocalMatrix.MultiplyPoint(src.transform.localToWorldMatrix.MultiplyPoint(y.Offset)); return(new VRMSpringBoneColliderGroup.SphereCollider { Offset = offset, Radius = y.Radius }); }).ToArray(); } foreach (var src in go.transform.GetComponentsInChildren <VRMSpringBone>()) { // Copy VRMSpringBone var dst = dstSecondary.gameObject.AddComponent <VRMSpringBone>(); dst.m_comment = src.m_comment; dst.m_stiffnessForce = src.m_stiffnessForce; dst.m_gravityPower = src.m_gravityPower; dst.m_gravityDir = src.m_gravityDir; dst.m_dragForce = src.m_dragForce; if (src.m_center != null) { dst.m_center = map[src.m_center]; } dst.RootBones = src.RootBones.Select(x => map[x]).ToList(); dst.m_hitRadius = src.m_hitRadius; if (src.ColliderGroups != null) { dst.ColliderGroups = src.ColliderGroups .Select(x => map[x.transform].GetComponent <VRMSpringBoneColliderGroup>()).ToArray(); } } } #pragma warning disable 0618 { // meta(obsolete) var src = go.GetComponent <VRMMetaInformation>(); if (src != null) { src.CopyTo(root); } } #pragma warning restore 0618 { // meta var src = go.GetComponent <VRMMeta>(); if (src != null) { var dst = root.AddComponent <VRMMeta>(); dst.Meta = src.Meta; } } { // firstPerson var src = go.GetComponent <VRMFirstPerson>(); if (src != null) { src.CopyTo(root, map); } } { // humanoid var dst = root.AddComponent <VRMHumanoidDescription>(); var src = go.GetComponent <VRMHumanoidDescription>(); if (src != null) { dst.Avatar = src.Avatar; dst.Description = src.Description; } else { var animator = go.GetComponent <Animator>(); if (animator != null) { dst.Avatar = animator.avatar; } } } }
protected override void DidActivate(bool firstActivation, ActivationType type) { try { if (firstActivation) { _songListTableCellInstance = Resources.FindObjectsOfTypeAll <LevelListTableCell>().First(x => (x.name == "LevelListTableCell")); RectTransform container = new GameObject("CustomListContainer", typeof(RectTransform)).transform as RectTransform; container.SetParent(rectTransform, false); container.sizeDelta = new Vector2(60f, 0f); var newGameObj = new GameObject("CustomListTableView"); // Disable the new gameobject containing the tableview to avoid HMUI.Init error spam in the output_log newGameObj.SetActive(false); _customListTableView = newGameObj.AddComponent <TableView>(); _customListTableView.gameObject.AddComponent <RectMask2D>(); _customListTableView.transform.SetParent(container, false); (_customListTableView.transform as RectTransform).anchorMin = new Vector2(0f, 0f); (_customListTableView.transform as RectTransform).anchorMax = new Vector2(1f, 1f); (_customListTableView.transform as RectTransform).sizeDelta = new Vector2(0f, 60f); (_customListTableView.transform as RectTransform).anchoredPosition = new Vector3(0f, 0f); _customListTableView.SetPrivateField("_preallocatedCells", new TableView.CellsGroup[0]); _customListTableView.SetPrivateField("_isInitialized", false); _customListTableView.dataSource = this; newGameObj.SetActive(true); _customListTableView.didSelectCellWithIdxEvent += _customListTableView_didSelectRowEvent; if (includePageButtons) { if (_pageUpButton == null) { _pageUpButton = Instantiate(Resources.FindObjectsOfTypeAll <Button>().Last(x => (x.name == "PageUpButton")), container, false); (_pageUpButton.transform as RectTransform).anchoredPosition = new Vector2(0f, 30f); _pageUpButton.interactable = true; _pageUpButton.onClick.AddListener(delegate() { _customListTableView.PageScrollUp(); }); } if (_pageDownButton == null) { _pageDownButton = Instantiate(Resources.FindObjectsOfTypeAll <Button>().Last(x => (x.name == "PageDownButton")), container, false); (_pageDownButton.transform as RectTransform).anchoredPosition = new Vector2(0f, -30f); _pageDownButton.interactable = true; _pageDownButton.onClick.AddListener(delegate() { _customListTableView.PageScrollDown(); }); } } } base.DidActivate(firstActivation, type); } catch (Exception e) { Console.WriteLine("EXCEPTION IN CustomListViewController.DidActivate: " + e); } }
private void Initialize(VehicleDef def, int[] colors = null) { Definition = def; if (colors != null && colors[0] != -1) { SetColors(colors); } else { var defaultClrs = CarColors.GetCarDefaults(Definition.ModelName); if (defaultClrs != null) { SetColors(defaultClrs[UnityEngine.Random.Range(0, defaultClrs.Count)]); } else { Debug.LogWarningFormat("No colours defined for {0}!", def.GameName); } } name = Definition.GameName; _geometryParts = LoadGeometryParts(Definition); _frames = _geometryParts.AttachFrames(transform, MaterialFlags.Vehicle); var wheelFrame = _frames.FirstOrDefault(x => x.Name == "wheel"); if (wheelFrame == null) { Debug.LogWarningFormat("No wheels defined for {0}!", def.GameName); Destroy(gameObject); return; } var engineFrame = _frames.FirstOrDefault(x => x.Name == "engine"); if (engineFrame != null) { this.EngineTransform = engineFrame.transform; } var petrolcapFrame = _frames.FirstOrDefault(x => x.Name == "petrolcap"); if (petrolcapFrame != null) { this.PetrolcapTransform = petrolcapFrame.transform; } foreach (var frame in _frames) { if (!frame.Name.StartsWith("wheel_")) { continue; } if (!frame.Name.EndsWith("_dummy")) { continue; } var childFrames = _frames.Where(x => x.ParentIndex == frame.Index); // disable all children of wheel dummies foreach (var childFrame in childFrames) { childFrame.gameObject.SetActive(false); } var wheelAlignment = GetWheelAlignment(frame.Name); Wheel inst; // see if this wheel dummy has a wheel child var wheel = childFrames.FirstOrDefault(x => x.Name == "wheel"); if (wheel == null) { var copy = Instantiate(wheelFrame.transform); copy.SetParent(frame.transform, false); _wheels.Add(inst = new Wheel { Alignment = wheelAlignment, Parent = frame.transform, Child = copy, }); } else { // all children of wheel dummies get set to inactive so activate this one wheel.gameObject.SetActive(true); _wheels.Add(inst = new Wheel { Alignment = wheelAlignment, Parent = frame.transform, Child = wheel.transform, }); } if (inst.IsLeftHand) { frame.transform.Rotate(Vector3.up, 180.0f); } inst.Complement = _wheels.FirstOrDefault(x => (x.Alignment & WheelAlignment.LeftRightMask) != (inst.Alignment & WheelAlignment.LeftRightMask) && (x.Alignment & WheelAlignment.FrontMidRearMask) == (inst.Alignment & WheelAlignment.FrontMidRearMask)); if (inst.Complement != null) { inst.Complement.Complement = inst; } } InitializePhysics(); this.Health = this.MaxHealth = Mathf.Pow(this.HandlingData.Mass, VehicleManager.Instance.massToHealthExponent); //this.SetupDoorsHingeJoints(); var frontSeat = GetPart("ped_frontseat"); var backSeat = GetPart("ped_backseat"); if (frontSeat != null) { var frontSeatMirror = new GameObject("ped_frontseat").transform; frontSeatMirror.SetParent(frontSeat.parent, false); frontSeatMirror.localPosition = Vector3.Scale(frontSeat.localPosition, new Vector3(-1f, 1f, 1f)); if (frontSeat.localPosition.x > 0f) { AttachSeat(frontSeat, SeatAlignment.FrontRight); AttachSeat(frontSeatMirror, SeatAlignment.FrontLeft); } else { AttachSeat(frontSeatMirror, SeatAlignment.FrontRight); AttachSeat(frontSeat, SeatAlignment.FrontLeft); } DriverTransform = GetSeat(SeatAlignment.FrontLeft).Parent; } if (backSeat != null) { var backSeatMirror = new GameObject("ped_backseat").transform; backSeatMirror.SetParent(backSeat.parent, false); backSeatMirror.localPosition = Vector3.Scale(backSeat.localPosition, new Vector3(-1f, 1f, 1f)); if (backSeat.localPosition.x > 0f) { AttachSeat(backSeat, SeatAlignment.BackRight); AttachSeat(backSeatMirror, SeatAlignment.BackLeft); } else { AttachSeat(backSeatMirror, SeatAlignment.BackRight); AttachSeat(backSeat, SeatAlignment.BackLeft); } } // Add vehicle damage /* * var dam = gameObject.AddComponent<VehicleDamage>(); * dam.damageParts = new Transform[] { transform.GetChild(0).Find("engine") }; * dam.deformMeshes = gameObject.GetComponentsInChildren<MeshFilter>(); * dam.displaceParts = gameObject.GetComponentsInChildren<Transform>().Where(x => x.GetComponent<Frame>() != null || x.GetComponent<FrameContainer>() != null).ToArray(); * dam.damageFactor = VehicleAPI.constDamageFactor; * dam.collisionIgnoreHeight = -.4f; * dam.collisionTimeGap = .1f; * * //OptimizeVehicle(); * * dam.deformColliders = gameObject.GetComponentsInChildren<MeshCollider>(); */ gameObject.SetLayerRecursive(Layer); SetupHighDetailMesh(); }
void LocateBackLink(LinkScript link, bool allowCreate = false) { NodeInstance from = link.GetComponentInParent<NodeInstance>(); NodeInstance to = link.to; link.backLink = to.GetComponentsInChildren<LinkScript>().ToList().FirstOrDefault(other => { if (other.to != from) { return false; } var testObject = new GameObject("TestObject").transform; var otherParent = other.transform.parent; testObject.SetParent(to.transform, worldPositionStays: false); other.transform.SetParent(testObject, worldPositionStays: true); testObject.SetParent(link.transform, worldPositionStays: false); var result = Extensions.Close(other.transform, from.transform); other.transform.SetParent(otherParent, worldPositionStays: false); DestroyImmediate(testObject.gameObject); return result; }); if (link.backLink == null) { if (!allowCreate) { Debug.LogError(string.Format("No backlink detected: {0} {1}", from.name, link.name)); } else { Debug.LogFormat(string.Format("No backlink detected: {0} {1}", from.name, link.name)); var backlinkObject = new GameObject(GenerateLinkName(link.to, from) + " (backlink)"); var backlink = backlinkObject.AddComponent<LinkScript>(); backlink.to = from; backlinkObject.transform.SetParent(from.transform); backlinkObject.transform.Reset(); backlinkObject.transform.SetParent(link.transform, worldPositionStays: true); var linkFolder = LinkFolder(link.to); backlinkObject.transform.SetParent(linkFolder, worldPositionStays: false); link.backLink = backlink; Debug.LogFormat("Backlink created: {0} {1} - {2} {3}", from.name, link.name, to.name, link.backLink.name); backlink.backLink = link; Debug.LogFormat("Backlink set: {0} {1} - {2} {3}", to.name, link.backLink.name, from.name, link.name); } } else { Debug.LogFormat("Backlink set: {0} {1} - {2} {3}", from.name, link.name, to.name, link.backLink.name); } }