AddComponent() public method

public AddComponent ( Type componentType ) : Component
componentType System.Type
return Component
Exemplo n.º 1
0
	static void AddHeatMap ()
	{
		GameObject go = new GameObject("GA_HeatMap");
		go.AddComponent<GA_HeatMapRenderer>();
		go.AddComponent<GA_HeatMapDataFilter>();
		Selection.activeObject = go;
	}
Exemplo n.º 2
0
    void AddClusterScripts(GameObject iObject, bool iChildren)
    {
        //MiddleVRTools.Log("AddCluster to " + iObject);
        //print("AddCluster to " + iObject);
        {
            if (iObject.GetComponent<VRShareTransform>() == null)
            {
                VRShareTransform script = iObject.AddComponent<VRShareTransform>() as VRShareTransform;
                script.Start();
            }

            if (iObject.GetComponent<VRApplySharedTransform>() == null)
            {
                VRApplySharedTransform script = iObject.AddComponent<VRApplySharedTransform>() as VRApplySharedTransform;
                script.Start();
            }
        }

        if( iChildren == true )
        {
            foreach (Transform child in iObject.transform)
            {
                GameObject childObject = child.gameObject;

                //print("Child : " + childObject);
                AddClusterScripts(childObject, true);
            }
        }
    }
Exemplo n.º 3
0
        /// <summary>
        /// Creates a blocker that covers the entire screen.
        /// </summary>
        /// <param name="onClosed">The callback which is called whenever the blocker is clicked and closed</param>
        /// <param name="sortingOrder">The SortingOrder for the blocker canvas, this value should be higher then any canvas that shouldn't receive input and lower then any canvas that should receive input</param>
        /// <param name="sortingLayerID">The layerID for the blocker canvas</param>
        public static void CreateBlocker(UnityAction onClosed, int sortingOrder, int sortingLayerID)
        {
            GameObject go = new GameObject("BlockerCanvas");
            Canvas canvas = go.AddComponent<Canvas>();
            go.AddComponent<GraphicRaycaster>();

            canvas.renderMode = RenderMode.ScreenSpaceOverlay;
            canvas.sortingLayerID = sortingLayerID;
            canvas.sortingOrder = sortingOrder;

            GameObject blocker = new GameObject("Blocker");

            RectTransform transform = blocker.AddComponent<RectTransform>();
            transform.SetParent(go.transform, false);
            transform.anchorMin = Vector3.zero;
            transform.anchorMax = Vector3.one;
            transform.offsetMin = transform.offsetMax = Vector2.zero;

            Image image = blocker.AddComponent<Image>();
            image.color = Color.clear;

            Button button = blocker.AddComponent<Button>();
            button.onClick.AddListener(() =>
            {
                UnityEngine.Object.Destroy(go);
                onClosed();
            });
        }
Exemplo n.º 4
0
 void Start()
 {
     lCamera = new GameObject( "lCamera" );
     lCamera.AddComponent<Camera>();
     lCamera.AddComponent<GUILayer>();
     lCamera.AddComponent("FlareLayer");
     lCamera.camera.CopyFrom(Camera.main);
     rCamera = (GameObject) Instantiate(lCamera, transform.position, transform.rotation);
     rCamera.name = "rCamera";
     lCamera.transform.parent = Camera.main.transform;
     rCamera.transform.parent = Camera.main.transform;
     parallax = new GameObject( "parallax" );
     parallax.transform.parent = Camera.main.transform;
     parallax.transform.localPosition = Vector3.zero;
     Vector3 parallaxPosition = parallax.transform.localPosition;
     parallaxPosition.z = parallaxDistance;
     parallax.transform.localPosition = parallaxPosition;
     camera.enabled = false;
     lCamera.camera.rect = new Rect(0, 0, 0.5f, 1);
     rCamera.camera.rect = new Rect(0.5f, 0, 0.5f, 1);
     lCamera.transform.localPosition = Vector3.zero;
     rCamera.transform.localPosition = Vector3.zero;
     Vector3 cameraPosition = lCamera.transform.localPosition;
     cameraPosition.x = -eyeDistance;
     lCamera.transform.localPosition = cameraPosition;
     cameraPosition.x = eyeDistance;
     rCamera.transform.localPosition = cameraPosition;
 }
Exemplo n.º 5
0
        public static void CreateNewUI()
        {
            GameObject mainCamera = GameObject.Find("Main Camera");
            if (mainCamera != null)
                GameObject.DestroyImmediate(mainCamera);

            GameObject uiObj = new GameObject("UI");
            uiObj.layer = (int)UnityLayerDef.UI;
            var canvas = uiObj.AddComponent<Canvas>();
            canvas.renderMode = RenderMode.ScreenSpaceOverlay;
            uiObj.AddComponent<CanvasScaler>();
            uiObj.AddComponent<GraphicRaycaster>();

            var evtSystemObj = new GameObject("EventSystem");
            evtSystemObj.AddComponent<EventSystem>();
            evtSystemObj.AddComponent<StandaloneInputModule>();
            evtSystemObj.AddComponent<TouchInputModule>();

            GameObject cameraObj = new GameObject("Camera");
            cameraObj.layer = (int)UnityLayerDef.UI;

            Camera camera = cameraObj.AddComponent<Camera>();
            camera.clearFlags = CameraClearFlags.Skybox;
            camera.depth = 0;
            camera.backgroundColor = Color.grey;
            camera.cullingMask = 1 << (int)UnityLayerDef.UI;
            camera.orthographicSize = 1f;
            camera.orthographic = true;
            camera.nearClipPlane = -2f;
            camera.farClipPlane = 2f;

            camera.gameObject.AddComponent<AudioListener>();

            Selection.activeGameObject = uiObj;
        }
Exemplo n.º 6
0
    void Awake()
    {
        // create empty(transform only) game object in scene with default position (0,0,0)
        GameObject myObj = new GameObject();
        myObj.transform.position = new Vector3(0, 3, 0);
        // add sprite renderer component
        myObj.AddComponent<SpriteRenderer>();

        // create texture from resource file
        myTexture = Resources.Load<Texture2D>("ProceduralSprite/100_px") as Texture2D;

        // A) store sprite > store component > assign spite to component property
        mySprite = Sprite.Create(myTexture, new Rect(25,25,75,75), new Vector2(0f, 0f));
        SpriteRenderer myObjComponent = myObj.GetComponent<SpriteRenderer>();
        myObjComponent.sprite = mySprite;

        // B) direct assign
        // myObj.GetComponent<SpriteRenderer>().sprite = Sprite.Create(myTexture, new Rect(0, 0, myTexture.width, myTexture.height), new Vector2(0.5f, 0f));

        // 1)----
        // load previously created animator controller as runtimeAnimationConroller
        myRTimeAnimator = Resources.Load<RuntimeAnimatorController>("ProceduralSprite/Cube") as RuntimeAnimatorController;
        // add animator component to GO and assign animator controller
        myObj.AddComponent<Animator>();
        myObj.GetComponent<Animator>().runtimeAnimatorController = myRTimeAnimator;

        // 2)----
        // alternative way (direct assing)
        // myObj.AddComponent<Animator>();
        // myObj.GetComponent<Animator>().runtimeAnimatorController = Resources.Load<RuntimeAnimatorController>("ProceduralSprite/Cube") as RuntimeAnimatorController;

    }
Exemplo n.º 7
0
		public static Far Create (VoxelTerrain land)
		{
			GameObject obj = new GameObject("Far");
			obj.transform.parent = land.transform;
			obj.transform.localPosition = Vector3.zero;
			
			Far far = obj.AddComponent<Far>();
			far.land = land;
			
			obj.AddComponent<MeshRenderer>();
			far.filter = obj.AddComponent<MeshFilter>();
			//far.filter.sharedMesh = new Mesh();
			
			far.GetComponent<Renderer>().sharedMaterial = land.terrainMaterial;
//			if (land.hideChunks) far.transform.hideFlags = HideFlags.HideInHierarchy;

			//hiding wireframe
			#if UNITY_EDITOR
			UnityEditor.EditorUtility.SetSelectedWireframeHidden(obj.GetComponent<Renderer>(), land.hideWire);
			
			//copy static flag
			UnityEditor.StaticEditorFlags flags = UnityEditor.GameObjectUtility.GetStaticEditorFlags(land.gameObject);
			UnityEditor.GameObjectUtility.SetStaticEditorFlags(obj, flags);
			#endif

			return far;
		}
Exemplo n.º 8
0
    void CreateCanvas()
    {
        if( !_didCreateUiStuff )
        {
            _didCreateUiStuff = true;

            //Create the UI canvas game object
            canvasRoot = new GameObject( "Canvas" );
            var canvas = canvasRoot.AddComponent<Canvas>();
            canvas.renderMode = RenderMode.ScreenSpaceOverlay;
            var cs = canvasRoot.AddComponent<CanvasScaler>();
            cs.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
            cs.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
            cs.referenceResolution = new Vector2(800,600);

            //create our ui prefab
            uiPrefab = new GameObject( "UItext" );
            uiPrefab.transform.position = new Vector3( 1000, 10000 );
            var txt = uiPrefab.AddComponent<Text>();
            txt.font = Resources.GetBuiltinResource( typeof( Font ), "Arial.ttf" ) as Font;
            txt.text = "Some text";
            txt.horizontalOverflow = HorizontalWrapMode.Overflow;
            txt.color = Color.white;
            txt.resizeTextForBestFit = true;

            // Make a recycle bin for it
            var recycleBin = new TrashManRecycleBin()
            {
                prefab = uiPrefab
            };
            TrashMan.manageRecycleBin( recycleBin );
        }
    }
Exemplo n.º 9
0
    public GUITextObj GetGUIText(int LayerNum)
    {
        int Count = 0;
        GUITextObj TmpTextObj;
        GameObject tmpGameObj;

        //Search guitext buffer for available object
        for (Count=0;Count<pTextBuffer.Count;Count++)
        {
            TmpTextObj = (GUITextObj) pTextBuffer[Count];
            if (TmpTextObj.GUIActive == false)
            {
                //Flag the object as used
                TmpTextObj.GUIActive = true;
                //Set the objects layer
                TmpTextObj.GameObj.layer = LayerNum;
                //Return object
                return TmpTextObj;
            }
        }

        //No available object, so allocate more
        int BuffIdx = 0;
        int BuffSize = pTextBuffer.Count;
        for (Count=0;Count<AllocBlockSize;Count++)
        {
            //Create new guitext object
            tmpGameObj = new GameObject();
            BuffIdx = BuffSize + Count;
            tmpGameObj.name = "GUIText" + BuffIdx.ToString();
            tmpGameObj.AddComponent("GUIText");
            tmpGameObj.AddComponent("Animator");
            tmpGameObj.AddComponent("GUITextObj");

            //Set a child of guitextmgr
            tmpGameObj.transform.parent = gameObject.transform;

            //Add to buffer
            TmpTextObj = (GUITextObj) tmpGameObj.GetComponent(typeof(GUITextObj));
            TmpTextObj.GUIActive = false;
            pTextBuffer.Add(TmpTextObj);
        }

        //Search guitext buffer for available object
        for (Count=0;Count<pTextBuffer.Count;Count++)
        {
            TmpTextObj = (GUITextObj) pTextBuffer[Count];
            if (TmpTextObj.GUIActive == false)
            {
                //Flag the object as used
                TmpTextObj.GUIActive = true;
                //Set the objects layer
                TmpTextObj.GameObj.layer = LayerNum;
                //Return object
                return TmpTextObj;
            }
        }

        return null;
    }
    // Update is called once per frame
    void Update()
    {
        if (leftController == -1) {
            leftController = SteamVR_Controller.GetDeviceIndex(SteamVR_Controller.DeviceRelation.Leftmost);
            if (leftController != -1 && leftController != 0)
            {
                Debug.Log("Left controller is: " + leftController);

                leftControllerObject = GameObject.Find("Device" + leftController.ToString());
                leftControllerObject.AddComponent<BoxCollider>();
                leftControllerObject.AddComponent<controllerIndexKeeper>().controllerIndex = leftController;
                leftControllerObject.tag = "controller";
            }

        }
        if (rightController == -1)
        {
            rightController = SteamVR_Controller.GetDeviceIndex(SteamVR_Controller.DeviceRelation.Rightmost);

            if (rightController != -1 && rightController != 0)
            {
                Debug.Log("Right controller is: " + rightController);

                rightControllerObject = GameObject.Find("Device" + rightController.ToString());
                rightControllerObject.AddComponent<BoxCollider>();
                rightControllerObject.AddComponent<controllerIndexKeeper>().controllerIndex = rightController;
                rightControllerObject.tag = "controller";
            }

        }
    }
Exemplo n.º 11
0
    public static void UseExistingOrCreateNewMainCamera()
    {
        GameObject tempCamera;
        GameObject targetLookAt;
        TP_Camera myCamera;

        if (Camera.mainCamera != null)
        {
            tempCamera = Camera.mainCamera.gameObject;
        }
        else
        {
            tempCamera = new GameObject("Main Camera");
            tempCamera.AddComponent("Camera");
            tempCamera.tag = "MainCamera";
            tempCamera.AddComponent("TP_Camera");
        }
        myCamera = tempCamera.GetComponent("TP_Camera") as TP_Camera;

        targetLookAt = GameObject.Find("targetLookAt") as GameObject;

        if (targetLookAt == null)
        {
            targetLookAt = new GameObject("targetLookAt");
            targetLookAt.transform.position = Vector3.zero;
        }

        myCamera.TargetLookAt = targetLookAt.transform;
    }
Exemplo n.º 12
0
	GameObject CreateChild (int x, int z)
	{
		GameObject lvObject = new GameObject ();
		
		lvObject.name = "Grid Cell";
		lvObject.transform.parent = transform;
		lvObject.transform.localPosition = new Vector3 ((float)x, 0.0f, (float)z);

		lvObject.AddComponent<MeshRenderer> ();

		lvObject.GetComponent<MeshRenderer> ().material = cellMaterialValid;

		CellStatus cellStatus = lvObject.AddComponent<CellStatus> ();
		cellStatus.avaiable = true;
		cellStatus.CellId = GetGridId (x, z);
	
		Mesh lvMesh = CreateMesh ();
		lvMesh.vertices = new Vector3[] {
			MeshVertex (0, 0),
			MeshVertex (0, 1),
			MeshVertex (1, 0),
			MeshVertex (1, 1),
		};

		lvObject.AddComponent<MeshFilter> ().mesh = lvMesh;
		lvObject.tag = "GridCell";
		lvObject.AddComponent<MeshCollider> ();
		
		return lvObject;
	}
Exemplo n.º 13
0
    private CapsuleCollider AddHipCollider(GameObject hipObject) {
        Rigidbody rb = hipObject.AddComponent<Rigidbody>();
        if (rb != null) {
            rb.mass = 1;
            rb.useGravity = false;
            rb.isKinematic = true;
            //rb.collisionDetectionMode = CollisionDetectionMode.Continuous;
        }

        CapsuleCollider collider = hipObject.AddComponent<CapsuleCollider>();
        if (collider != null) {
            collider.isTrigger = true;
            if (proximitySpeed) {
                collider.height = 0.80f;
                collider.radius = 1f;
            } else {
                collider.height = 1.60f;
                collider.radius = 0.20f;
            }
            collider.center = new Vector3(-hipObject.transform.localPosition.x, 0.2f, -hipObject.transform.localPosition.z);
        }


        return collider;
    }
Exemplo n.º 14
0
        public static GameObject CreateDecal(Material mat, Rect uvCoords, float scale)
        {
            GameObject decal = new GameObject();
            decal.name = "Decal" + decal.GetInstanceID();

            decal.AddComponent<MeshFilter>().sharedMesh = DecalMesh("DecalMesh" + decal.GetInstanceID(), mat, uvCoords, scale);
            decal.AddComponent<MeshRenderer>().sharedMaterial = mat;

            #if UNITY_5
            decal.GetComponent<MeshRenderer>().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
            #else
            decal.GetComponent<MeshRenderer>().castShadows = false;
            #endif

            qd_Decal decalComponent = decal.AddComponent<qd_Decal>();

            decalComponent.SetScale(scale);
            decalComponent.SetTexture( (Texture2D)mat.mainTexture );
            decalComponent.SetUVRect(uvCoords);

            #if DEBUG
            decal.AddComponent<qd_DecalDebug>();
            #endif

            return decal;
        }
Exemplo n.º 15
0
 public static void CreateSpriteGameObject()
 {
     GameObject n = new GameObject ();
     n.AddComponent<SpriteRenderer> ();
     n.AddComponent<SpriteAnimation> ();
     n.name = "New Animated Sprite";
 }
Exemplo n.º 16
0
    void DrawBarrier()
    {
        for (int i = 0; i < points.Count; i++)
        {
            Vector3 p = points[i];
            p -= new Vector3(0.5f, 0.5f, 0);
            p.x *= (float) Screen.width / Screen.height;
            p *= 15;
            points[i] = p;
        }

        GameObject container = new GameObject();
        container.transform.parent = topSideTran;
        container.AddComponent<Mover>();
        DrawDestruct dd = container.AddComponent<DrawDestruct>();
        dd.cost = points.Count * energyCost;
        dd.drawClass = this;
        dd.bonusScore = 5;
        Destroy(container, selfDestructTime);

        for (int i = 0; i < points.Count - 1; i++)
        {
            GameObject obj = (GameObject) GameObject.Instantiate(linePrefab, points[i], Quaternion.identity);

            obj.transform.position = Vector3.Lerp(points[i], points[i+1], 0.5f);
            obj.tag = "Barrier";
            obj.transform.LookAt(points[i+1]);
            Vector3 s = obj.transform.localScale;
            obj.transform.localScale = new Vector3(s.x, s.y, Vector3.Distance(points[i], points[i+1]));
            obj.transform.parent = container.transform;
        }
    }
Exemplo n.º 17
0
    private TriggerParent triggerParent; //this is a utility class, that lets us check if the player is close to the coins "bounds sphere trigger"

    #endregion Fields

    #region Methods

    //private GUIManager gui;
    //setup
    void Awake()
    {
        //gui = FindObjectOfType(typeof(GUIManager)) as GUIManager ;
        if(tag != "Pickup")
        {
            tag = "Pickup";

        }
        bubbleBlowing = GameObject.FindGameObjectWithTag("Player").GetComponent<BubbleBlowing>();
        GetComponent<Collider>().isTrigger = true;
        triggerParent = GetComponentInChildren<TriggerParent>();
        //if no trigger bounds are attached to coin, set them up
        if(!triggerParent)
        {
            GameObject bounds = new GameObject();
            bounds.name = "Bounds";
            bounds.AddComponent<SphereCollider>();
            bounds.GetComponent<SphereCollider>().radius = 3f;
            bounds.GetComponent<SphereCollider>().isTrigger = true;
            bounds.transform.parent = transform;
            bounds.transform.position = transform.position;
            bounds.AddComponent<TriggerParent>();
            triggerParent = GetComponentInChildren<TriggerParent>();
            triggerParent.tagsToCheck = new string[1];
            triggerParent.tagsToCheck[0] = "Player";
        }
        for(int i = 0; i < transform.childCount; i++)
        {
            this.transform.GetChild(i).gameObject.layer = LayerMask.NameToLayer("Items");
        }
    }
Exemplo n.º 18
0
    // Use this for initialization
    void Start()
    {
        //general setup
        menu = GetComponentInParent<Menu>();
        options = new List<MenuViewOptionBasic>();
        GetComponentsInChildren<MenuViewOptionBasic>(options);
        toDraw = true;
        if(options == null) options = new List<MenuViewOptionBasic>();
        //Setup view
        viewObject = new GameObject("MenuViewBasic");
        viewObject.transform.SetParent(transform);
        canvas = viewObject.AddComponent<Canvas>();
        canvas.renderMode = RenderMode.ScreenSpaceCamera;
        canvas.worldCamera = drawCamera;
        canvas.planeDistance = 1f;
        viewObject.AddComponent<CanvasScaler>();
        viewObject.AddComponent<GraphicRaycaster>();
        //Setup textbox
        textbox = new GameObject("TextBox");
        textPosition = textbox.AddComponent<RectTransform>();
        textPosition.SetParent(viewObject.transform);
        textPosition.localPosition = new Vector3(position.x,position.y, 0);
        textbox.AddComponent<CanvasRenderer>();

        text = textbox.AddComponent<Text>();
        text.font = textFont;
        text.alignment = TextAnchor.MiddleCenter;
        text.color = new Color(color.r, color.g, color.b);
        if(options.Count > 0) text.text = options[menu.CurOption].optionText;
    }
Exemplo n.º 19
0
    void create()
    {
        //creation de la fenetre
        GameObject newCanvas = new GameObject("Canvas");
        Canvas ca = newCanvas.AddComponent<Canvas>();
        ca.renderMode = RenderMode.ScreenSpaceOverlay;
        //ajout de ces composents
        newCanvas.AddComponent<CanvasScaler>();
        newCanvas.AddComponent<GraphicRaycaster>();
        //ajout du panel
        GameObject panel = new GameObject("Panel");
        panel.AddComponent<CanvasRenderer>();
        Image i = panel.AddComponent<Image>();
        i.color = new Color(0, 0, 0, 0.4f);
        //le panel appartient a la fenetre
        panel.transform.SetParent(newCanvas.transform, false);

        // position et taille de la barre de spell
        panel.transform.position = new Vector3((Screen.width / 2), 1, 0);
        panel.GetComponent<RectTransform>().sizeDelta = new Vector2(Screen.width - (Screen.width / 7), Screen.height / 5);

        //ajout des cases de spell pour chaque capacité du joueur
        for (int ic = 0; ic < transform.GetComponents<capacity>().Length; ic++)
        {
            GameObject text = new GameObject(transform.GetComponents<capacity>()[ic].name);
            text.AddComponent<Text>().name = transform.GetComponents<capacity>()[ic].name;
            text.GetComponent<Text>().text = transform.GetComponents<capacity>()[ic].K.ToString();
            text.GetComponent<Text>().font = (Font)Resources.GetBuiltinResource(typeof(Font), "Arial.ttf");
            text.transform.SetParent(newCanvas.transform, false);
            text.transform.position = new Vector3(((Screen.width - (Screen.width / 7)) / transform.GetComponents<capacity>().Length) * ic + (Screen.width / 7), 1, 0);
            LC.Add(transform.GetComponents<capacity>()[ic]);
            transform.GetComponents<capacity>()[ic].T = text.GetComponent<Text>();
        }
    }
Exemplo n.º 20
0
        public void Substract()
        {
            var stopWatch = new Stopwatch();
            stopWatch.Start();

            var csgA = new CSG.CSG();
            csgA.Construct(A.GetComponent<MeshFilter>().sharedMesh, A.transform, 0);

            var csgB = new CSG.CSG();
            csgB.Construct(B.GetComponent<MeshFilter>().sharedMesh, B.transform, 1);

            var substract = csgA.Substract(csgB);
            var newMesh = substract.ToMesh();

            Result = new GameObject("Substract");
            var defObj = Result.AddComponent<DefaultObject>();
            var meshFilter = Result.AddComponent<MeshFilter>();
            meshFilter.sharedMesh = newMesh;
            var renderer = Result.AddComponent<MeshRenderer>();
            renderer.sharedMaterials = new Material[] { A.GetComponent<MeshRenderer>().sharedMaterial, B.GetComponent<MeshRenderer>().sharedMaterial };

            if (DeleteOriginal)
            {
                Object.DestroyImmediate(A);
                Object.DestroyImmediate(B);
            }

            stopWatch.Stop();
            defObj.GenerationTimeMS = stopWatch.ElapsedMilliseconds;
        }
Exemplo n.º 21
0
    void AddNewMoving(GameObject obj)
    {
        Destroy (obj.GetComponent<Moving> ());

        obj.AddComponent<RotateObject> ();
        obj.AddComponent<JumpSlerpObject> ();
    }
Exemplo n.º 22
0
 void OnEnable()
 {
     GameObject go = new GameObject ("One Shot Audio");
     go.AddComponent<TimedDestruction> ().seconds = clip.length;
     go.AddComponent<AudioSource> ().clip = clip;
     go.GetComponent<AudioSource> ().Play ();
 }
Exemplo n.º 23
0
    public IStack initialise(Vector3 centroid, Vector3 stackTwist, float scale, Color stackColour)
    {
        stack = new GameObject("Torus");
        torus = stack.AddComponent<TorusPrimitive>();

        torus.OuterRadius = scale;
        torus.InnerRadius = 0.2f * scale;
        //torus.Sides = 32;
        //torus.Segments = 32;

        torus.UpdatePrimitive ();

        stackRigidBody = stack.AddComponent<Rigidbody>();
        stackRigidBody.useGravity = false;
        stackRigidBody.detectCollisions = false;

        stack.transform.position = centroid;

        currentRotationX = stackTwist.x;
        currentRotationY = stackTwist.y;
        currentRotationZ = stackTwist.z;
        stack.transform.Rotate (stackTwist);

        stack.transform.localScale = new Vector3(scale, scale, scale);

        stack.GetComponent<Renderer>().material.color = stackColour;
        return this;
    }
Exemplo n.º 24
0
    void BuildingSphereField()
    {
        for(int y=0; y<fieldHeight; y++)
        {
            for(int z=0; z<fieldDepth; z++)
            {
                shiftX = 0.0f;

                for(int x=0; x<fieldWidth; x++){
                    int randomNumber = Random.Range(1,3);
                    float randomSize = Mathf.Round(Random.Range(0.3f,0.6f) * 100.0f) / 100.0f;
                    shiftX += (randomSize + 0.2f);
                    switch(randomNumber)
                    {
                    case 1: fieldPart = GameObject.CreatePrimitive (PrimitiveType.Sphere);
                            fieldPart.GetComponent<SphereCollider>().material = Resources.Load("darkroom/BouncingBob") as PhysicMaterial;
                            break;
                    case 2: fieldPart = GameObject.CreatePrimitive (PrimitiveType.Cube);
                        fieldPart.GetComponent<BoxCollider>().material = Resources.Load("darkroom/BouncingBob") as PhysicMaterial;
                            break;
                    }

                    fieldPart.transform.localScale = new Vector3 (randomSize, randomSize, randomSize);
                    fieldPart.GetComponent<MeshRenderer>().material = Resources.Load("darkroom/darkroom") as Material;
                    fieldPart.AddComponent<BallBehavior>();
                    Rigidbody rb = fieldPart.AddComponent<Rigidbody> ();
                    rb.useGravity = false;
                    fieldPart.transform.parent = transform;
                    fieldPart.transform.localPosition = new Vector3 (-shiftX, y*-0.7f, z*-0.7f);
                    fieldPart.name = "lightBall";
                    fieldPart.layer = LayerMask.NameToLayer("Ignore Raycast");
                }
            }
        }
    }
		public void CreatePrefab()
		{
			if (prefabAtmosphere == null)
			{
				prefabAtmosphere = new GameObject ("RefractiveAtmosphere");
				prefabAtmosphere.SetActive (false);
				var mf = prefabAtmosphere.AddComponent<MeshFilter> ();
				var mr = prefabAtmosphere.AddComponent<MeshRenderer> ();
				mr.castShadows = false;
				mr.receiveShadows = false;

				var material = new Material (Shaders.RefractiveAtmosphere);
				var _normals = new Texture2D (4, 4, TextureFormat.ARGB32, false);
				_normals.LoadImage (Textures.RefractiveAtmosphereNormals);
				material.SetTexture ("_BumpMap", _normals);
				material.SetTextureScale ("_BumpMap", new Vector2 (4f, 4f));
				material.SetVector ("_BumpMapOffset", new Vector4 (0, 0, 1, 0));

				mr.sharedMaterial = material;

				var sphere = GameObject.CreatePrimitive (PrimitiveType.Sphere);
				var sphereMesh = sphere.GetComponent<MeshFilter> ().mesh;
				DestroyImmediate (sphere);
				mf.sharedMesh = sphereMesh;

				var behaviour = prefabAtmosphere.AddComponent<RefractiveAtmosphere> ();

				prefabAtmosphere.transform.localScale = Vector3.one * 1250f;

				DontDestroyOnLoad (prefabAtmosphere);
			}
		}
Exemplo n.º 26
0
    void Awake()
    {
        var sky = GetComponent<Skybox>();
        Material skymat = sky != null ? sky.material : RenderSettings.skybox;
        if (skymat == null) {
          enabled = false;
          return;
        }

        skybox = new GameObject(skymat.name + "SkyMesh");
        skybox.transform.parent = transform;
        skybox.transform.localPosition = Vector3.zero;
        skybox.layer = layer;

        var filter = skybox.AddComponent<MeshFilter>();
        filter.mesh = _CreateSkyboxMesh();

        Material mat = new Material(Shader.Find("Cardboard/SkyboxMesh"));
        var render = skybox.AddComponent<MeshRenderer>();
        render.sharedMaterials = new Material[] {
        new Material(mat) { mainTexture = skymat.GetTexture("_FrontTex") },
        new Material(mat) { mainTexture = skymat.GetTexture("_LeftTex")  },
        new Material(mat) { mainTexture = skymat.GetTexture("_BackTex")  },
        new Material(mat) { mainTexture = skymat.GetTexture("_RightTex") },
        new Material(mat) { mainTexture = skymat.GetTexture("_UpTex")    },
        new Material(mat) { mainTexture = skymat.GetTexture("_DownTex")  }
        };
        render.castShadows = false;
        render.receiveShadows = false;
    }
Exemplo n.º 27
0
    private void SpawnPlayer()
    {
        GameObject groundMesh = GameObject.Find("groundMesh");
        if(groundMesh == null || player != null){
            return;
        }

        float x = 175.0f; //groundMesh.renderer.bounds.max.x+(groundMesh.renderer.bounds.min.x*0.5f);
        float y = groundMesh.renderer.bounds.max.y+(groundMesh.renderer.bounds.min.y*0.5f);
        float z = 175.0f; //groundMesh.renderer.bounds.max.z+(groundMesh.renderer.bounds.min.z);

         player = GameObject.CreatePrimitive(PrimitiveType.Capsule);

        player.transform.localScale = new Vector3(3.469746f,4.222249f,3.469746f);
        float height = player.renderer.bounds.max.y-player.renderer.bounds.min.y;
        Vector3 center = new Vector3(x,y+height,z);
        player.transform.position = center;
        player.AddComponent<Rigidbody>();
        Rigidbody rb = player.GetComponent<Rigidbody>();
        rb.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ |  RigidbodyConstraints.FreezePositionX |  RigidbodyConstraints.FreezePositionZ ;
        //transform.parent = player.transform;

        player.AddComponent<CameraTraveler>();
        player.GetComponent<CameraTraveler>().player = player;
    }
Exemplo n.º 28
0
    public static void createInstance()
    {
        GameObject tmpObj = GameObject.Find("PersistentObj");
        if(tmpObj != null)
        {
            instance = tmpObj;
        }
        else
        {
            // Basic object shell.
            instance = new GameObject("PersistentObj");
            instance.transform.position = new Vector3(0,0,0);

            // Persistent object components.
            // (Other components may be attached from within other scripts once you obtain an instance via getInstance())
            //instance.AddComponent<ServerComRequester>();
            instance.AddComponent<SoundPlayerScript>();
            DatastoreScript ds = instance.AddComponent<DatastoreScript>();

            // Store versioning info in memory. (Primarily needed by the saving system to detect old or new save data).
            int dayValue = 6;//23;
            int monthValue = 1;//10;
            int yearValue = 2015;//2014;
            int versionForDay = 0;

            ds.insertData("GameVersionData",new SaveVersioningInfo(dayValue,monthValue,yearValue,versionForDay,""));

            // Make sure that the object is not destroyed when new scenes are loaded.
            UnityEngine.MonoBehaviour.DontDestroyOnLoad(instance);
        }
    }
Exemplo n.º 29
0
    public static GameObject CreatePlane(Vector2 size)
    {
        size *= 0.5f;
        Mesh planeMesh = new Mesh();
        planeMesh.name = "CustomPlane";

        //set vertices
        Vector3[] vertices = {
            new Vector3(-size.x, -size.y, 0f),
            new Vector3(size.x, -size.y, 0f),
            new Vector3(size.x, size.y, 0f),
            new Vector3(-size.x, size.y, 0f)};
        planeMesh.vertices = vertices;
        //set uvs
        Vector2[] uvs = {Vector2.zero, Vector2.up, Vector2.one, Vector2.right};
        planeMesh.uv = uvs;
        //set triangles
        int[] triangles = {0, 1, 2, 0, 2, 3};
        planeMesh.triangles = triangles;
        planeMesh.RecalculateNormals();

        //Create gameobject
        GameObject plane = new GameObject("CustomPlane");
        MeshFilter _meshFilter = plane.AddComponent<MeshFilter>();
        _meshFilter.mesh = planeMesh;
        plane.AddComponent<MeshRenderer>();
        plane.AddComponent<MeshCollider>();
        plane.transform.position = Vector3.zero;

        return plane;
    }
Exemplo n.º 30
0
        public EditorModel(GameObject assetPrefab)
        {
            prefab = assetPrefab;

            saveAssetFolder = System.IO.Path.GetDirectoryName(AssetDatabase.GetAssetPath(prefab));

            assetInstance = GameObject.Instantiate(assetPrefab) as GameObject;
            assetInstance.name = assetPrefab.name;
            assetInstance.SetActive(true);

            // Check for LocalSettings on the prefab and use that if possible
            LocalSettings = assetInstance.GetComponentInChildren<LocalSettings>();
            if (LocalSettings != null) {
            UseLocalSettings = true;
            BlobModel = assetInstance.AddComponent<ABlobModel>().InitWithExistingBlob(LocalSettings.gameObject);
            } else {
            Mesh blobMesh = AssetDatabase.LoadAssetAtPath("Assets/BlobOMatic/BlobMesh.asset", typeof(Mesh)) as Mesh;
            BlobModel = assetInstance.AddComponent<ABlobModel>().Init(blobMesh);
            if (!ICanHasShadow) return; // Not a valid model, bugger off!

            LocalSettings = BlobModel.BlobRenderer.gameObject.AddComponent<LocalSettings>().CopyGlobalSettings();

            saveAssetFolder +=  "/" + prefab.name + "WithBlob";
            }

            // Collect original layers and set everything to blob layer
            foreach (Transform t in assetInstance.GetComponentsInChildren<Transform>(true))
            originalLayers[t.gameObject] = t.gameObject.layer;
            assetInstance.SetLayerRecursively(BlobOMatic.EditorLayer);

            assetInstance.SetActive(false);
            assetInstance.SetHideFlagsRecursively(HideFlags.HideAndDontSave);

            RenderBlob();
        }
Exemplo n.º 31
0
            public void playGlobal(Vec3 position, Transform parent)
            {
                if (Global.Sfx.sfxVolume <= 0.0f)
                {
                    return;
                }

                GO obj = new GO();

                // Center in parent
                obj.transform.parent   = parent;
                obj.transform.position = position;

                AudioSource player = obj.AddComponent <AudioSource>();

                player.clip         = this.src;
                player.spatialBlend = 1.0f; // full-3D
                player.minDistance  = 0.5f;
                player.maxDistance  = 10.0f;
                player.volume       = Global.Sfx.sfxVolume;
                player.Play();
                obj.AddComponent <DestroyOnAudioDone>();
            }
Exemplo n.º 32
0
 static public int AddComponent(IntPtr l)
 {
     try {
         UnityEngine.GameObject self = (UnityEngine.GameObject)checkSelf(l);
         System.Type            a1;
         checkType(l, 2, out a1);
         var ret = self.AddComponent(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Exemplo n.º 33
0
 static public int AddComponent(IntPtr l)
 {
     try {
                     #if DEBUG
         var    method     = System.Reflection.MethodBase.GetCurrentMethod();
         string methodName = GetMethodName(method);
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.BeginSample(methodName);
                     #else
         Profiler.BeginSample(methodName);
                     #endif
                     #endif
         int argc = LuaDLL.lua_gettop(l);
         if (argc == 1)
         {
             UnityEngine.GameObject self = (UnityEngine.GameObject)checkSelf(l);
             var ret = self.AddComponent <UnityEngine.Component>();
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         else if (argc == 2)
         {
             UnityEngine.GameObject self = (UnityEngine.GameObject)checkSelf(l);
             System.Type            a1;
             checkType(l, 2, out a1);
             var ret = self.AddComponent(a1);
             pushValue(l, true);
             pushValue(l, ret);
             return(2);
         }
         pushValue(l, false);
         LuaDLL.lua_pushstring(l, "No matched override function AddComponent to call");
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
             #if DEBUG
     finally {
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.EndSample();
                     #else
         Profiler.EndSample();
                     #endif
     }
             #endif
 }
Exemplo n.º 34
0
 static int AddComponent(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         UnityEngine.GameObject obj  = (UnityEngine.GameObject)ToLua.CheckObject(L, 1, typeof(UnityEngine.GameObject));
         System.Type            arg0 = (System.Type)ToLua.CheckObject(L, 2, typeof(System.Type));
         UnityEngine.Component  o    = obj.AddComponent(arg0);
         ToLua.Push(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Exemplo n.º 35
0
    public void CreatePathTarget()
    {
        UnityEngine.GameObject editorObject = UnityEngine.GameObject.CreatePrimitive(UnityEngine.PrimitiveType.Cube);
        int index = UnityEngine.GameObject.FindObjectsOfType <AreaObject>().Count(i => i.name.StartsWith("PATH_TARGET_"));

        editorObject.name = $"PATH_TARGET_{index}";
        editorObject.AddComponent <AreaObject>();
        editorObject.GetComponent <AreaObject>().parent     = TargetArea;
        editorObject.GetComponent <AreaObject>().masterType = typeof(AreaTile);

        editorObject.transform.SetParent(TargetArea.transform);
        editorObject.transform.position = TargetArea.transform.position;

        editorObject.GetComponent <AreaObject>().tileParent = new AreaTile();
        createPathTarget = false;
    }
Exemplo n.º 36
0
    private void StartTweenPos(UnityEngine.GameObject go)
    {
        if (null == go)
        {
            return;
        }
        TweenPosition tweenPos = go.GetComponent <TweenPosition>();

        if (tweenPos != null)
        {
            Destroy(tweenPos);
        }
        tweenPos          = go.AddComponent <TweenPosition>();
        tweenPos.from     = go.transform.localPosition;
        tweenPos.to       = new UnityEngine.Vector3(0, 0, 0);
        tweenPos.duration = 0.2f;
    }
Exemplo n.º 37
0
    static public void WaitInput(GO caller, int column, Actions action)
    {
        if (waitFunc != null || waitCaller != null)
        {
            return;
        }

        axis[] arr = getArr(column);

        KeyLogger kl = caller.GetComponentInChildren <KeyLogger>();

        if (kl == null)
        {
            kl = caller.AddComponent <KeyLogger>();
        }
        kl.enabled = true;

        waitCaller = kl;
        waitFunc   = kl.StartCoroutine(_waitInput(arr, action));
    }
Exemplo n.º 38
0
        public static UnityEngine.GameObject NewIterM(UnityEngine.GameObject origin)
        {
            UnityEngine.GameObject backobj = UnityEngine.GameObject.Instantiate(origin, origin.transform.position, origin.transform.rotation) as UnityEngine.GameObject;
            backobj.transform.parent     = XOGloble.IterM.transform;
            backobj.transform.localScale = origin.transform.lossyScale;
            backobj.name = XOUtil.Path(origin);
            XOCp_MarkIntermediate mi = backobj.AddComponent <XOCp_MarkIntermediate>();

            mi.OriginInstID = origin.GetInstanceID();
            mi.goOrigin     = origin;
            backobj.SetActive(true);

            XOCp_OptimizerHandler xoh = XOGloble.Root.GetComponent <XOCp_OptimizerHandler>();

            if (xoh != null)
            {
                xoh.AddObjLstByShaderMaterial(backobj);
            }

            XOUtil.Display(backobj, false);
            return(backobj);
        }
Exemplo n.º 39
0
        private void AddGrabbable(GameObject obj)
        {
            if (!obj)
            {
                return;
            }

            var grabbable        = obj.GetComponent <HVRGrabbable>();
            var physicsGrabbable = obj.GetComponent <HVRPhysicsGrabbable>();

            if (!grabbable && !physicsGrabbable)
            {
                obj.AddComponent <HVRGrabbable>();
            }

            if (AddGrabPoints(obj))
            {
                AddGrabPoint(SelectedGrabPoints);
            }

            obj.SetExpandedRecursive(true);
        }
Exemplo n.º 40
0
        private void Start()
        {
            int cnt        = TriggerScaleAndLinkToParent.Length;
            int prefabsCnt = PrefabToLink.Length;

            for (int i = 0; i < cnt; ++i)
            {
                int prefabIdx = i < prefabsCnt ? i : prefabsCnt - 1;
                UnityEngine.GameObject obj      = new UnityEngine.GameObject("FbxTrigger");
                UnityEngine.GameObject childObj = Instantiate(PrefabToLink[prefabIdx]);
                childObj.transform.parent = obj.transform;

                Transform trigger = TriggerScaleAndLinkToParent[i];
                Picus.Utils.GO.Transformer.TransformTo(obj.transform, trigger.parent);
                obj.transform.parent = trigger.parent;

                Picus.Utils.GO.Finder.FindComponentAddIfNotExist <Picus.Utils.SortingLayer>(childObj).SortAllDeepFromParent();

                FbxTrigger script = obj.AddComponent <FbxTrigger>();
                script.Init(trigger, childObj, InheritRotation);
            }
        }
Exemplo n.º 41
0
    public void OnDrag(PointerEventData eventData)
    {
        if (!lineStartPoint.HasValue)
        {
            return;
        }

        if (valid_path)
        {
            return;
        }

        if (used == true)
        {
            Destroy(lines[nb_line]);
        }

        var lineEndPoint = GetMouseCameraPoint();
        var nextline     = new UnityEngine.GameObject();
        var lineRenderer = nextline.AddComponent <LineRenderer>();

        lines[nb_line] = nextline;

        if (obj_in.Getinstate() == 2)
        {
            lineRenderer.material = lineMaterialtrue;
        }
        else
        {
            lineRenderer.material = lineMaterialfalse;
        }

        lineRenderer.SetPositions(new Vector3[] { lineStartPoint.Value, lineEndPoint });
        lineRenderer.startWidth = lineWith;
        lineRenderer.endWidth   = lineWith;
        linesRend[nb_line]      = lineRenderer;
        used = true;
    }
Exemplo n.º 42
0
    public void registerGeometry(FS_ShadowSimple s, FS_MeshKey meshKey)
    {
        FS_ShadowManagerMesh m;

        if (meshKey.isStatic)
        {
            if (!shadowMeshesStatic.ContainsKey(meshKey.mat))
            {
                UnityEngine.GameObject g = new UnityEngine.GameObject("ShadowMeshStatic_" + meshKey.mat.name);
                g.transform.parent = transform;
                m = g.AddComponent <FS_ShadowManagerMesh>();
                m.shadowMaterial = s.shadowMaterial;
                m.isStatic       = true;
                shadowMeshesStatic.Add(meshKey.mat, m);
            }
            else
            {
                m = (FS_ShadowManagerMesh)shadowMeshesStatic[meshKey.mat];
            }
        }
        else
        {
            if (!shadowMeshes.ContainsKey(meshKey.mat))
            {
                UnityEngine.GameObject g = new UnityEngine.GameObject("ShadowMesh_" + meshKey.mat.name);
                g.transform.parent = transform;
                m = g.AddComponent <FS_ShadowManagerMesh>();
                m.shadowMaterial = s.shadowMaterial;
                m.isStatic       = false;
                shadowMeshes.Add(meshKey.mat, m);
            }
            else
            {
                m = (FS_ShadowManagerMesh)shadowMeshes[meshKey.mat];
            }
        }
        m.registerGeometry(s);
    }
Exemplo n.º 43
0
    static UnityEngine.GameObject AddEasyTouch(bool c)
    {
        if (UnityEngine.GameObject.FindObjectOfType(typeof(EasyTouch)) == null)
        {
            UnityEngine.GameObject easyTouch = new UnityEngine.GameObject("EasyTouch");
            EasyTouch easy = easyTouch.AddComponent <EasyTouch>();

            if (c)
            {
                easy.useBroadcastMessage = false;
            }
            else
            {
                easy.useBroadcastMessage = true;
            }
            return(easyTouch);
        }
        else
        {
            EditorUtility.DisplayDialog("Warning", "EasyTouch is already exist in your scene", "OK");
            return(null);
        }
    }
Exemplo n.º 44
0
 void SyncEventListeners( )
 {
     if (null == event_UnityEngine_GameObject_Instance_0 || false == m_RegisteredForEvents)
     {
         event_UnityEngine_GameObject_Instance_0 = uScript_MasterComponent.LatestMaster;
         if (null != event_UnityEngine_GameObject_Instance_0)
         {
             {
                 uScript_Update component = event_UnityEngine_GameObject_Instance_0.GetComponent <uScript_Update>();
                 if (null == component)
                 {
                     component = event_UnityEngine_GameObject_Instance_0.AddComponent <uScript_Update>();
                 }
                 if (null != component)
                 {
                     component.OnUpdate      += Instance_OnUpdate_0;
                     component.OnLateUpdate  += Instance_OnLateUpdate_0;
                     component.OnFixedUpdate += Instance_OnFixedUpdate_0;
                 }
             }
         }
     }
 }
Exemplo n.º 45
0
 public void HandleCustomProperties(UnityEngine.GameObject gameObject,
                                    IDictionary <string, string> props)
 {
     // Simply add a component to our GameObject
     if (props.ContainsKey("AddComp"))
     {
         try
         {
             string          type           = props["AddComp"];
             Type            T              = TypeMapping.GetType(type);
             Component       comp           = gameObject.AddComponent(T);
             ITiledComponent tiledComponent = comp as ITiledComponent;
             if (tiledComponent != null)
             {
                 tiledComponent.SetupFromProperties(props);
             }
         }
         catch (Exception e)
         {
             Debug.LogError(e.Message);
         }
     }
 }
Exemplo n.º 46
0
 public static void EnsureInitialized()
 {
     try
     {
         if (EventPump.Instance == null)
         {
             lock (s_Lock)
             {
                 if (EventPump.Instance == null)
                 {
                     UnityEngine.GameObject parent = new UnityEngine.GameObject("Kinect Desktop Event Pump");
                     EventPump.Instance = parent.AddComponent <Helper.EventPump>();
                     DontDestroyOnLoad(parent);
                 }
             }
         }
     }
     catch
     {
         UnityEngine.Debug.LogError("Events must be registered on the main thread.");
         return;
     }
 }
Exemplo n.º 47
0
        public static T CreateSingletonMonoBehaviour <T>() where T : MonoBehaviour
        {
            T instance = UnityEngine.Object.FindObjectOfType <T>();

            if (instance != null)
            {
                var instances = UnityEngine.Object.FindObjectsOfType <T>();

                if (instances.Length == 1)
                {
                    throw new Exception(typeof(T) + " Instance Existed!");
                }

                throw new Exception(typeof(T) + " Instance Existed! And Type Count : " + instances.Length.ToString());
            }
            var gameObject = new UnityEngine.GameObject("Singleton No Copy");

            UnityEngine.Object.DontDestroyOnLoad(gameObject);

            instance = gameObject.AddComponent <T>();

            return(instance);
        }
Exemplo n.º 48
0
    //event nodes

    //property nodes

    //method nodes
   #pragma warning restore 414

    //functions to refresh properties from entities

    void SyncUnityHooks( )
    {
        SyncEventListeners( );
        if (null == local_4_UnityEngine_GameObject || false == m_RegisteredForEvents)
        {
            local_4_UnityEngine_GameObject = GameObject.Find("SFXPlayer") as UnityEngine.GameObject;
        }
        //if our game object reference was changed then we need to reset event listeners
        if (local_4_UnityEngine_GameObject_previous != local_4_UnityEngine_GameObject || false == m_RegisteredForEvents)
        {
            //tear down old listeners

            local_4_UnityEngine_GameObject_previous = local_4_UnityEngine_GameObject;

            //setup new listeners
        }
        if (null == owner_Connection_1 || false == m_RegisteredForEvents)
        {
            owner_Connection_1 = parentGameObject;
            if (null != owner_Connection_1)
            {
                {
                    uScript_Button component = owner_Connection_1.GetComponent <uScript_Button>();
                    if (null == component)
                    {
                        component = owner_Connection_1.AddComponent <uScript_Button>();
                    }
                    if (null != component)
                    {
                        component.OnButtonClick += Instance_OnButtonClick_0;
                        component.OnButtonDown  += Instance_OnButtonDown_0;
                        component.OnButtonUp    += Instance_OnButtonUp_0;
                    }
                }
            }
        }
    }
Exemplo n.º 49
0
        void PathResources()
        {
            int count = 0;

            foreach (GenericSpawner spawner in UnityEngine.Resources.FindObjectsOfTypeAll <GenericSpawner>())
            {
                GameObject.Destroy(spawner);
            }
            foreach (KeyValuePair <string, object> spawnlist in SpawnLists)
            {
                var currentSpawnlist = (Dictionary <string, object>)spawnlist.Value;
                var newlist          = new List <GenericSpawnerSpawnList.GenericSpawnInstance>();
                foreach (object pair in (List <object>)currentSpawnlist["spawnList"])
                {
                    var currentspawninstance = (Dictionary <string, object>)pair;
                    var newspawnlistdata     = new GenericSpawnerSpawnList.GenericSpawnInstance();
                    newspawnlistdata.forceStaticInstantiate = false;
                    newspawnlistdata.numToSpawnPerTick      = Convert.ToInt32(currentspawninstance["numToSpawnPerTick"]);
                    newspawnlistdata.prefabName             = currentspawninstance["prefabName"].ToString();

                    newspawnlistdata.targetPopulation = Convert.ToInt32(currentspawninstance["targetPopulation"]);
                    newspawnlistdata.useNavmeshSample = true;
                    newspawnlistdata.spawned          = new List <UnityEngine.GameObject>();
                    newlist.Add(newspawnlistdata);
                }
                var gameobject = new UnityEngine.GameObject();
                var generic    = gameobject.AddComponent <GenericSpawner>();
                generic.transform.position = new Vector3(Convert.ToSingle(currentSpawnlist["position_x"]), Convert.ToSingle(currentSpawnlist["position_y"]), Convert.ToSingle(currentSpawnlist["position_z"]));
                generic.initialSpawn       = true;
                generic._spawnList         = newlist;
                generic.radius             = Convert.ToSingle(currentSpawnlist["radius"]);
                genericspawn_serverload.Invoke(generic, new object[] { });
                generic.SpawnThink();
                count++;
            }
            Puts(string.Format("{0} custom resource spawns where loaded!", count.ToString()));
        }
Exemplo n.º 50
0
    /// <summary>
    /// 初始化界面
    /// </summary>
    void Init()
    {
        if (m_grid_grid.transform.childCount > 0)
        {
            UpdateAnimalGridList();
            return;
        }

        List <LandAndFarmDataBase> landList = GameTableManager.Instance.GetTableList <LandAndFarmDataBase>();

        uint animalID = DataManager.Manager <HomeDataManager>().animalID;

        landList = landList.FindAll((LandAndFarmDataBase ld) => { return(ld.dwID == animalID); });

        for (int i = 0; i < landList.Count; i++)
        {
            UnityEngine.GameObject obj = UIManager.GetResGameObj(GridID.Uihomeanimalgrid) as UnityEngine.GameObject;
            obj = Instantiate(obj);

            obj.transform.parent        = m_grid_grid.transform;
            obj.transform.localPosition = Vector3.zero;
            obj.transform.localScale    = Vector3.one;
            obj.transform.localRotation = Quaternion.identity;

            UIHomeAnimalGrid homeAnimalGrid = obj.GetComponent <UIHomeAnimalGrid>();
            if (homeAnimalGrid == null)
            {
                homeAnimalGrid = obj.AddComponent <UIHomeAnimalGrid>();
            }

            obj.SetActive(true);
            homeAnimalGrid.Init(landList[i].indexID);
        }

        m_grid_grid.Reposition();
    }
Exemplo n.º 51
0
        public void Init(int row, int colomn)
        {
            if (row < 2 || colomn < 2)
            {
                return;
            }
            ClearCubeContainer();
            m_CubeItems.Clear();
            m_TargetList.Clear();
            m_Row    = row;
            m_Colomn = colomn;

            int zoomMultiple = m_Row > m_Colomn ? m_Row : m_Colomn;

            m_MinSlideDistance             = zoomMultiple - 2 == 0? GlobalConfig.ITEM_HALFSLIDEDISTANCE: GlobalConfig.ITEM_HALFSLIDEDISTANCE / (2 * (zoomMultiple - 2));
            m_CameraViewHeight             = zoomMultiple * 10;
            Camera.main.transform.position = new Vector3(0, m_CameraViewHeight, 0.5f);
            Kernel.AssetManager.InstantiateGameObjectAsync((GF.Asset.AssetKey)AssetKey.Prefabs_Box001_prefab, (GF.Asset.AssetKey key, UnityEngine.Object tmpObj) =>
            {
                m_CubePrefab = tmpObj as GameObject;
                m_CubePrefab.AddComponent <BoxCollider>();
                InitCubes(m_CubePrefab);
            });
        }
Exemplo n.º 52
0
    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            lineStartPoint = GetMouseCameraPoint();
        }
        else if (Input.GetMouseButtonUp(0))
        {
            if (!lineStartPoint.HasValue)
            {
                return;
            }

            var lineEndPoint = GetMouseCameraPoint();
            var gameObject   = new UnityEngine.GameObject();
            var lineRenderer = gameObject.AddComponent <LineRenderer>();
            lineRenderer.material = lineMaterial;
            lineRenderer.SetPositions(new Vector3[] { lineStartPoint.Value, lineEndPoint });
            lineRenderer.startWidth = lineWith;
            lineRenderer.endWidth   = lineWith;

            lineStartPoint = null;
        }
    }
        /////////////////////////////////////////////////////////////////////////////////
        public UIRenderer(Noesis.FrameworkElement content, UnityEngine.Vector2 offscreenSize,
                          UnityEngine.GameObject target)
        {
            _rendererId = Noesis_CreateRenderer(Noesis.FrameworkElement.getCPtr(content).Handle);

            _content = content;
            _root    = VisualTreeHelper.GetRoot(_content);

            _offscreenSize = offscreenSize;
            _mousePos      = UnityEngine.Input.mousePosition;

            _target = target;

            _texture = FindTexture();
            if (IsRenderToTexture)
            {
                _textureCamera                  = _target.AddComponent <Camera>();
                _textureCamera.clearFlags       = CameraClearFlags.SolidColor;
                _textureCamera.backgroundColor  = new UnityEngine.Color(0.0f, 0.0f, 0.0f, 0.0f);
                _textureCamera.renderingPath    = RenderingPath.Forward;
                _textureCamera.depthTextureMode = DepthTextureMode.None;
#if !UNITY_4_6 && !UNITY_5_0 && !UNITY_5_1
                _textureCamera.opaqueSortMode = UnityEngine.Rendering.OpaqueSortMode.NoDistanceSort;
#endif
                _textureCamera.transparencySortMode          = TransparencySortMode.Orthographic;
                _textureCamera.clearStencilAfterLightingPass = false;
                _textureCamera.allowHDR            = false;
                _textureCamera.useOcclusionCulling = false;
                _textureCamera.cullingMask         = 0;
                _textureCamera.targetTexture       = _texture;
            }

            _targetCamera = _target.GetComponent <Camera>();

            _Panels.Add(_rendererId, _target.GetComponent <NoesisGUIPanel>());
        }
Exemplo n.º 54
0
        void Awake()
        {
            if (!enabled)
            {
                return;
            }

            m_camera = Camera.main;
            Application.targetFrameRate = -1;

            UnityEngine.GameObject frameCounter = new UnityEngine.GameObject("Frame Counter");

            m_TextMeshPro      = frameCounter.AddComponent <TextMeshPro>();
            m_TextMeshPro.font = Resources.Load <TMP_FontAsset>("Fonts & Materials/LiberationSans SDF");
            m_TextMeshPro.fontSharedMaterial = Resources.Load <Material>("Fonts & Materials/LiberationSans SDF - Overlay");


            m_frameCounter_transform = frameCounter.transform;
            m_frameCounter_transform.SetParent(m_camera.transform);
            m_frameCounter_transform.localRotation = Quaternion.identity;

            m_TextMeshPro.enableWordWrapping = false;
            m_TextMeshPro.fontSize           = 24;
            //m_TextMeshPro.FontColor = new Color32(255, 255, 255, 128);
            //m_TextMeshPro.edgeWidth = .15f;
            m_TextMeshPro.isOverlay = true;

            //m_TextMeshPro.FaceColor = new Color32(255, 128, 0, 0);
            //m_TextMeshPro.EdgeColor = new Color32(0, 255, 0, 255);
            //m_TextMeshPro.FontMaterial.renderQueue = 4000;

            //m_TextMeshPro.CreateSoftShadowClone(new Vector2(1f, -1f));

            Set_FrameCounter_Position(AnchorPosition);
            last_AnchorPosition = AnchorPosition;
        }
Exemplo n.º 55
0
    public static int AddComponent1_wrap(long L)
    {
        try
        {
            long VM       = FCLibHelper.fc_get_vm_ptr(L);
            long nThisPtr = FCLibHelper.fc_get_inport_obj_ptr(L);
            UnityEngine.GameObject obj = get_obj(nThisPtr);
            string arg0    = FCLibHelper.fc_get_string_a(L, 0);
            long   nRetPtr = 0;
            switch (arg0)
            {
            case "SkinnedMeshRenderer":
            {
                SkinnedMeshRenderer ret_obj = obj.AddComponent <SkinnedMeshRenderer>();
                nRetPtr = FCGetObj.PushObj <SkinnedMeshRenderer>(ret_obj);
            }
            break;

            case "Renderer":
            {
                Renderer ret_obj = obj.AddComponent <Renderer>();
                nRetPtr = FCGetObj.PushObj <Renderer>(ret_obj);
            }
            break;

            case "MeshRenderer":
            {
                MeshRenderer ret_obj = obj.AddComponent <MeshRenderer>();
                nRetPtr = FCGetObj.PushObj <MeshRenderer>(ret_obj);
            }
            break;

            case "Animation":
            {
                Animation ret_obj = obj.AddComponent <Animation>();
                nRetPtr = FCGetObj.PushObj <Animation>(ret_obj);
            }
            break;

            case "Collider":
            {
                Collider ret_obj = obj.AddComponent <Collider>();
                nRetPtr = FCGetObj.PushObj <Collider>(ret_obj);
            }
            break;

            case "BoxCollider":
            {
                BoxCollider ret_obj = obj.AddComponent <BoxCollider>();
                nRetPtr = FCGetObj.PushObj <BoxCollider>(ret_obj);
            }
            break;

            case "BoxCollider2D":
            {
                BoxCollider2D ret_obj = obj.AddComponent <BoxCollider2D>();
                nRetPtr = FCGetObj.PushObj <BoxCollider2D>(ret_obj);
            }
            break;

            case "MeshCollider":
            {
                MeshCollider ret_obj = obj.AddComponent <MeshCollider>();
                nRetPtr = FCGetObj.PushObj <MeshCollider>(ret_obj);
            }
            break;

            case "SphereCollider":
            {
                SphereCollider ret_obj = obj.AddComponent <SphereCollider>();
                nRetPtr = FCGetObj.PushObj <SphereCollider>(ret_obj);
            }
            break;

            case "Rigidbody":
            {
                Rigidbody ret_obj = obj.AddComponent <Rigidbody>();
                nRetPtr = FCGetObj.PushObj <Rigidbody>(ret_obj);
            }
            break;

            case "Camera":
            {
                Camera ret_obj = obj.AddComponent <Camera>();
                nRetPtr = FCGetObj.PushObj <Camera>(ret_obj);
            }
            break;

            case "AudioSource":
            {
                AudioSource ret_obj = obj.AddComponent <AudioSource>();
                nRetPtr = FCGetObj.PushObj <AudioSource>(ret_obj);
            }
            break;

            case "Transform":
            {
                Transform ret_obj = obj.AddComponent <Transform>();
                nRetPtr = FCGetObj.PushObj <Transform>(ret_obj);
            }
            break;

            case "Component":
            {
                Component ret_obj = obj.AddComponent <Component>();
                nRetPtr = FCGetObj.PushObj <Component>(ret_obj);
            }
            break;

            case "ParticleSystem":
            {
                ParticleSystem ret_obj = obj.AddComponent <ParticleSystem>();
                nRetPtr = FCGetObj.PushObj <ParticleSystem>(ret_obj);
            }
            break;

            case "Light":
            {
                Light ret_obj = obj.AddComponent <Light>();
                nRetPtr = FCGetObj.PushObj <Light>(ret_obj);
            }
            break;

            case "Button":
            {
                Button ret_obj = obj.AddComponent <Button>();
                nRetPtr = FCGetObj.PushObj <Button>(ret_obj);
            }
            break;

            case "Text":
            {
                Text ret_obj = obj.AddComponent <Text>();
                nRetPtr = FCGetObj.PushObj <Text>(ret_obj);
            }
            break;

            default:
                break;
            }
            long ret_ptr = FCLibHelper.fc_get_return_ptr(L);
            FCLibHelper.fc_set_value_wrap_objptr(VM, ret_ptr, nRetPtr);
        }
        catch (Exception e)
        {
            Debug.LogException(e);
        }
        return(0);
    }
Exemplo n.º 56
0
        public static void ExtractMaterialMeshes(UnityEngine.GameObject rObject)
        {
            if (rObject == null)
            {
                return;
            }
            if (!rObject.activeInHierarchy)
            {
                return;
            }

            // If this object has a mesh, extract it
            MeshFilter lMeshFilter = rObject.GetComponent <MeshFilter>();

            if (lMeshFilter == null)
            {
                return;
            }

            // Ensure we're only extracting rendered meshes
            MeshRenderer lMeshRenderer = rObject.GetComponent <MeshRenderer>();

            if (lMeshRenderer == null)
            {
                return;
            }

            // We need to break the mesh into it's sub mesh parts so we can assign materials
            Mesh     lMesh     = null;
            Material lMaterial = null;

            int lSubMeshCount = lMeshFilter.sharedMesh.subMeshCount;

            for (int i = 0; i < lSubMeshCount; i++)
            {
                // This is easy, use the shared instance
                if (i == 0)
                {
                    lMesh     = lMeshFilter.sharedMesh;
                    lMaterial = lMeshRenderer.sharedMaterial;
                }
                // Process each sub-mesh individually
                else
                {
                    // Create a mesh from the sub-mesh
                    lMesh = CreateMesh(lMeshFilter.sharedMesh, i);

                    // Find the material it's using
                    if (lMeshRenderer.sharedMaterials.Length > i)
                    {
                        lMaterial = lMeshRenderer.sharedMaterials[i];
                    }
                    else
                    {
                        lMaterial = lMeshRenderer.sharedMaterials[lMeshRenderer.sharedMaterials.Length - 1];
                    }
                }

                string newname = "split-" + rObject.name + i;
                UnityEngine.GameObject newobj = new UnityEngine.GameObject(newname);
                newobj.transform.parent     = XOGloble.IterM.transform;
                newobj.transform.position   = lMeshFilter.transform.position;
                newobj.transform.rotation   = lMeshFilter.transform.rotation;
                newobj.transform.localScale = lMeshFilter.transform.lossyScale;


                newobj.isStatic = true;


                MeshFilter lMergedMeshFilter = newobj.AddComponent(typeof(MeshFilter)) as MeshFilter;
                lMergedMeshFilter.mesh = lMesh;


                // CombineInstance[] lMeshes = new CombineInstance[1];
                // lMeshes[0].transform = lMeshFilter.transform.localToWorldMatrix;
                // lMeshes[0].mesh = lMesh;

                lMergedMeshFilter.sharedMesh.name = "Merged Mesh of " + lSubMeshCount + " items";
                // lMergedMeshFilter.sharedMesh.CombineMeshes(lMeshes, true);
                // Unwrapping.GenerateSecondaryUVSet(lMergedMeshFilter.sharedMesh);



                MeshRenderer lMergedMeshRenderer = newobj.AddComponent(typeof(MeshRenderer)) as MeshRenderer;
                lMergedMeshRenderer.sharedMaterial = lMaterial;

                XOCp_OptimizerHandler xoh = XOGloble.Root.GetComponent <XOCp_OptimizerHandler>();
                if (xoh != null)
                {
                    xoh.nlst.Add(newobj);
                    xoh.AddObjLstByShaderMaterial(newobj);
                }
            }
        }
Exemplo n.º 57
0
 static void AddMeToScene()
 {
     ModAPI.Log.Write("Checker added to scene.");
     UnityEngine.GameObject GO = new UnityEngine.GameObject("__Checker__");
     GO.AddComponent <Checker>();
 }
Exemplo n.º 58
0
 public static T AddComponent <T>(this UnityEngine.GameObject go, T toAdd) where T : Component
 {
     return(go.AddComponent <T>().GetCopyOf(toAdd) as T);
 }
Exemplo n.º 59
0
        void Start()
        {
            for (int i = 0; i < NumberOfNPC; i++)
            {
                if (SpawnType == 0)
                {
                    // TextMesh Pro Implementation
                    UnityEngine.GameObject go = new UnityEngine.GameObject();
                    go.transform.position = new Vector3(Random.Range(-95f, 95f), 0.25f, Random.Range(-95f, 95f));

                    TextMeshPro textMeshPro = go.AddComponent <TextMeshPro>();

                    textMeshPro.autoSizeTextContainer = true;
                    textMeshPro.rectTransform.pivot   = new Vector2(0.5f, 0);

                    textMeshPro.alignment     = TextAlignmentOptions.Bottom;
                    textMeshPro.fontSize      = 96;
                    textMeshPro.enableKerning = false;

                    textMeshPro.color = new Color32(255, 255, 0, 255);
                    textMeshPro.text  = "!";

                    // Spawn Floating Text
                    floatingText_Script           = go.AddComponent <TextMeshProFloatingText>();
                    floatingText_Script.SpawnType = 0;
                }
                else if (SpawnType == 1)
                {
                    // TextMesh Implementation
                    UnityEngine.GameObject go = new UnityEngine.GameObject();
                    go.transform.position = new Vector3(Random.Range(-95f, 95f), 0.25f, Random.Range(-95f, 95f));

                    TextMesh textMesh = go.AddComponent <TextMesh>();
                    textMesh.font = Resources.Load <Font>("Fonts/ARIAL");
                    textMesh.GetComponent <Renderer>().sharedMaterial = textMesh.font.material;

                    textMesh.anchor   = TextAnchor.LowerCenter;
                    textMesh.fontSize = 96;

                    textMesh.color = new Color32(255, 255, 0, 255);
                    textMesh.text  = "!";

                    // Spawn Floating Text
                    floatingText_Script           = go.AddComponent <TextMeshProFloatingText>();
                    floatingText_Script.SpawnType = 1;
                }
                else if (SpawnType == 2)
                {
                    // Canvas WorldSpace Camera
                    UnityEngine.GameObject go = new UnityEngine.GameObject();
                    Canvas canvas             = go.AddComponent <Canvas>();
                    canvas.worldCamera = Camera.main;

                    go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);
                    go.transform.position   = new Vector3(Random.Range(-95f, 95f), 5f, Random.Range(-95f, 95f));

                    TextMeshProUGUI textObject = new UnityEngine.GameObject().AddComponent <TextMeshProUGUI>();
                    textObject.rectTransform.SetParent(go.transform, false);

                    textObject.color     = new Color32(255, 255, 0, 255);
                    textObject.alignment = TextAlignmentOptions.Bottom;
                    textObject.fontSize  = 96;
                    textObject.text      = "!";

                    // Spawn Floating Text
                    floatingText_Script           = go.AddComponent <TextMeshProFloatingText>();
                    floatingText_Script.SpawnType = 0;
                }
            }
        }
Exemplo n.º 60
0
        void Start()
        {
            TMP_FontAsset fontAsset = null;

            // Create Dynamic Font Asset for the given font file.
            switch (Benchmark)
            {
            case BenchmarkType.TMP_SDF_MOBILE:
                fontAsset = TMP_FontAsset.CreateFontAsset(SourceFontFile, 90, 9, GlyphRenderMode.SDFAA, 256, 256, AtlasPopulationMode.Dynamic);
                break;

            case BenchmarkType.TMP_SDF__MOBILE_SSD:
                fontAsset = TMP_FontAsset.CreateFontAsset(SourceFontFile, 90, 9, GlyphRenderMode.SDFAA, 256, 256, AtlasPopulationMode.Dynamic);
                fontAsset.material.shader = Shader.Find("TextMeshPro/Mobile/Distance Field SSD");
                break;

            case BenchmarkType.TMP_SDF:
                fontAsset = TMP_FontAsset.CreateFontAsset(SourceFontFile, 90, 9, GlyphRenderMode.SDFAA, 256, 256, AtlasPopulationMode.Dynamic);
                fontAsset.material.shader = Shader.Find("TextMeshPro/Distance Field");
                break;

            case BenchmarkType.TMP_BITMAP_MOBILE:
                fontAsset = TMP_FontAsset.CreateFontAsset(SourceFontFile, 90, 9, GlyphRenderMode.SMOOTH, 256, 256, AtlasPopulationMode.Dynamic);
                break;
            }

            for (int i = 0; i < NumberOfSamples; i++)
            {
                switch (Benchmark)
                {
                case BenchmarkType.TMP_SDF_MOBILE:
                case BenchmarkType.TMP_SDF__MOBILE_SSD:
                case BenchmarkType.TMP_SDF:
                case BenchmarkType.TMP_BITMAP_MOBILE:
                {
                    UnityEngine.GameObject go = new UnityEngine.GameObject();
                    go.transform.position = new Vector3(0, 1.2f, 0);

                    TextMeshPro textComponent = go.AddComponent <TextMeshPro>();
                    textComponent.font      = fontAsset;
                    textComponent.fontSize  = 128;
                    textComponent.text      = "@";
                    textComponent.alignment = TextAlignmentOptions.Center;
                    textComponent.color     = new Color32(255, 255, 0, 255);

                    if (Benchmark == BenchmarkType.TMP_BITMAP_MOBILE)
                    {
                        textComponent.fontSize = 132;
                    }
                }
                break;

                case BenchmarkType.TEXTMESH_BITMAP:
                {
                    UnityEngine.GameObject go = new UnityEngine.GameObject();
                    go.transform.position = new Vector3(0, 1.2f, 0);

                    TextMesh textMesh = go.AddComponent <TextMesh>();
                    textMesh.GetComponent <Renderer>().sharedMaterial = SourceFontFile.material;
                    textMesh.font     = SourceFontFile;
                    textMesh.anchor   = TextAnchor.MiddleCenter;
                    textMesh.fontSize = 130;

                    textMesh.color = new Color32(255, 255, 0, 255);
                    textMesh.text  = "@";
                }
                break;
                }
            }
        }