I have some childs on my main gameobject, what am I down wrong on the below code? I bassically want to access to the sprite renderer of the childs of my game object,
If I put that code on the direct child that have the sprite render I can access to the sprite with GetComponent, please if anyone know what can I do let me know
SpriteRenderer sprite;
private bool changeColorState = false;
public float time;
void Start(){
sprite = GetComponentsInChildren<SpriteRenderer>();
}
void Update(){
StartCoroutine(timeOfColorChange());
}
IEnumerator timeOfColorChange(){
yield return new WaitForSeconds(time);
if (changeColorState) {
chooseColor(.5f);
} else {
chooseColor(1f);
}
}
private void OnTriggerEnter2D(Collider2D otherObject){
if (otherObject.GetComponent<Player>()) {
changeColorState = true;
}
}
private void OnTriggerExit2D(Collider2D otherObject){
if (otherObject.GetComponent<Player>()) {
changeColorState = false;
}
}
public void chooseColor(float float1){
this.GetComponent<SpriteRenderer>().color = new Color(1f, 1f, 1f, float1);
}
I've tried GetComponentsOnChild but it's not working
You're not using the "sprite" variable inside chooseColor, where you're using GetComponent instead of GetComponentInChildren. Swap it for sprite.color and it should work.
Related
I Did apply some of the responses , most likely in the wrong way.. this is still not working with this RAYCAST. What am I doing wrong here?
Want to spawn a prefab, which is a a ball, this ball is flying forward on flick finger on the screen.
What I want is to spawn OnClick FEW/Multiple of this prefab.
, prefab is spawning on Raycast Hit, BUT.. when I am flicking the object EVERY prefab in the scene is moving in the same way.
If I flick first one in to the Left, it goes there, but If now I flick second one to right, BOTH go to the RIGHT, but I would like them to work independent. Maybe this is easy fix to this but I can't find answer. (I'm planning to have up to 30/50 of this prefabs, so attaching separate scripts would be bit time consuming)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallScript1 : MonoBehaviour
{
Vector2 startPos, endPos, direction;
float touchTimeStart, touchTimeFinish;
public float timeInterval = 5f;
public float throwForceInXandY = 1f;
public float throwForceinZ = 40f;
public static bool SpawnButtonAppear = true;
public static bool thrown = false;
public static bool moving = false;
public static bool fly = false;
public bool Pressed = false;
Rigidbody rb;
public GameObject player;
public Vector3 originalPos;
public GameObject playerPrefab;
string touched;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.isKinematic = true;
}
private void OnMouseDown()
{
PlayerTest.clicked = true;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit _hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out _hit))
{
touched = _hit.collider.tag;
if (touched == "Player")
{
Invoke("spawned", 0.5f);
}
}
}
if (touched == "Player")
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
touchTimeStart = Time.time;
startPos = Input.GetTouch(0).position;
}
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended)
{
fly = false;
touchTimeFinish = Time.time;
endPos = Input.GetTouch(0).position;
direction = startPos - endPos;
rb.isKinematic = false;
rb.AddForce(-direction.x * throwForceInXandY, -direction.y * throwForceInXandY, throwForceinZ * timeInterval);
BackWall.canSpawnNow = 1;
}
}
}
public void spawned()
{
GameObject spawnedprefab = Instantiate(playerPrefab, new Vector3(originalPos.y, originalPos.x, originalPos.z), Quaternion.identity);
Destroy(spawnedprefab, 5f);
}
The thrown variable is not declared inside your class, so when you set it to true you are setting it true for all the instances of the class.
Declare the bool thrown; inside the EnemySpawn class, so that OnMouseDown, only the corresponding intance's thrown variable is set to true.
I am creating a build in Unity 2019.4.12f1 and need to drag an object with Right Mouse button.
My C# skills are very limited, so far but i try.
This scripts is my attempt to be able to rotate a gameobject by holding right mouse button down and dragging ingame.
But it is wrong.
Can anyone help me correct it?ยด
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class mouseM : MonoBehaviour
{
bool dragging = false;
void Start()
{
if (Input.GetMouseButtonDown(1))
{
dragging = true;
}
}
void Update()
{
if (Input.GetMouseButtonDown(1))
{
yourOnMouseDownFunction();
dragging = true;
}
if (Input.GetMouseButtonUp(1))
{
yourOnMouseUpFunction();
dragging = false;
}
if (dragging)
{
yourOnMouseDragFunction();
}
}
}
I understood that You need to Drag Object in 3d World so Here is my Code just create new Script and attach to Object You Want to Drag it
Your Object that You need to Drag it should has a collider
using UnityEngine;
public class DragableObject : MonoBehaviour
{
private Vector3 mOffset;
private float mZCoord;
private void OnMouseDrag()
{
transform.position = GetMouseWorldPos() + mOffset;
}
private void OnMouseDown()
{
mZCoord = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
mOffset = transform.position - GetMouseWorldPos();
}
private Vector3 GetMouseWorldPos()
{
Vector3 mosePoint = Input.mousePosition;
mosePoint.z = mZCoord;
var result = Camera.main.ScreenToWorldPoint(mosePoint);
return result;
}
}
you can try it by adding it to sphere or cube and if you use custom shape you should insure that the collider is in suitable size or has a meshcollier
Demo
EDIT
using UnityEngine;
public class DragableObject : MonoBehaviour
{
private bool isMouseDragging;
private Vector3 screenPosition;
private Vector3 offset;
private GameObject target;
GameObject ReturnClickedObject(out RaycastHit hit)
{
GameObject targetObject = null;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray.origin, ray.direction * 10, out hit))
{
targetObject = hit.collider.gameObject;
}
return targetObject;
}
void Update()
{
if (Input.GetMouseButtonDown(1))
{
RaycastHit hitInfo;
target = ReturnClickedObject(out hitInfo);
if (target != null)
{
isMouseDragging = true;
Debug.Log("our target position :" + target.transform.position);
//Here we Convert world position to screen position.
screenPosition = Camera.main.WorldToScreenPoint(target.transform.position);
offset = target.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z));
}
}
if (Input.GetMouseButtonUp(1))
{
isMouseDragging = false;
}
if (isMouseDragging)
{
//tracking mouse position.
Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPosition.z);
//convert screen position to world position with offset changes.
Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenSpace) + offset;
//It will update target gameobject's current postion.
target.transform.position = currentPosition;
}
}
}
You could try the Input.GetMouseButton method, this should return a value depending on if the button is held pressed.
This one works too, if someone needs in the future.
This is for rotate though.
Sorry, i dont know why it wont let me post as code, so i post an image.
enter image description here
I have a test ad setup in my unity game. I am calling the IntAd function from the GameManager Script after the game is over. But the problem is when I click the close button in the ad, the ad reappears again and again. Please help me how can stop IntAd function after showing the ad.
public class AdsManager : MonoBehaviour
{
public static AdsManager instance;
private string playStoreID = "000000";
private string intAd = "video";
private string rewardedAd = "rewardedVideo";
private string bannerAd = "bannerAd";
public bool isTargrtPlayStore;
public bool isTestAd;
public static int start;
void Awake()
{
DontDestroyOnLoad(this.gameObject);
if (instance == null)
{
instance = this;
}
else
{
Destroy(this.gameObject);
}
}
private void Start()
{
InitializeAdvertisement();
}
private void InitializeAdvertisement()
{
if (isTargrtPlayStore)
{
Advertisement.Initialize(playStoreID, isTestAd);
return;
}
}
public void IntAd()
{
if (Advertisement.IsReady(intAd))
{
Advertisement.Show(intAd);
}
}
}
Here is GameManager Script-
public class GameManager : MonoBehaviour
{
public static GameManager instance;
public bool gameOver;
void Awake()
{
if (instance == null){
instance = this;
}
}
// Start is called before the first frame update
void Start()
{
gameOver = false;
}
// Update is called once per frame
void Update()
{
}
public void StartGame()
{
UiManager.instance.GameStart();
UiManager.instance.StartScore1();
ScoreManager.instance.startScore();
GameObject.Find("PlatformSpawner").GetComponent<PlatformSpawner>().StartSpawningPlatforms();
//AdsManager.instance.BannerAd();
}
public void GameOver()
{
UiManager.instance.GameOver();
ScoreManager.instance.stopScore();
gameOver = true;
AdsManager.instance.IntAd();
}
}
code to call GameOver function
void Update()
{
if (!started)
{
if (Input.GetMouseButtonDown(0))
{
rb.velocity = new Vector3(speed, 0, 0);
started = true;
GameManager.instance.StartGame();
}
}
if (!Physics.Raycast(transform.position, Vector3.down, 1f))
{
gameOver = true;
rb.velocity = new Vector3(0, -25f, 0);
Camera.main.GetComponent<CameraFollow>().gameOver = true;
GameManager.instance.GameOver();
}
The code you have calling GameManager.GameOver() is inside of Update() so it's going to get called every frame, and if !Physics.Raycast(transform.position, Vector3.down, 1f) is always true when the game is over (and not just true once), then it'll end up calling GameManager.GameOver() every frame which lines up with the behaviour that you're seeing.
You could resolve this by adding !gameOver to your if statement, that way it'll only go into the if statement once at the end of your game, and then upon gamestart you could flip gameOver back to false.
if (!Physics.Raycast(transform.position, Vector3.down, 1f) && !gameOver)
{
gameOver = true;
rb.velocity = new Vector3(0, -25f, 0);
Camera.main.GetComponent<CameraFollow>().gameOver = true;
GameManager.instance.GameOver();
}
Just do an if statement with a bool named GameEnd. Set it to false. Play the ad only if GameEnd is false. Rite after the ad instantiates, set GameEnd to true.
if (!Physics.Raycast(transform.position, Vector3.down, 1f))
{
bool GameEnd = false;
gameOver = true;
rb.velocity = new Vector3(0, -25f, 0);
Camera.main.GetComponent<CameraFollow>().gameOver = true;
if(! GameEnd)
{
GameManager.instance.GameOver();
GameEnd = true;
}
}
I'm not very good with Unity especially in AR, but I finally built my first AR game. However, there is one issue: when I place my game objects on the plane, I want them to be still and want them to move when I touch the display. Is there a way to disable the touch hit or whatever it is called?
......................................................................................................................................................................................................................................................................................................................................................................................................
enter code here
[RequireComponent(typeof(ARRaycastManager))]
public class PlaceOnPlane : MonoBehaviour
{
[SerializeField]
[Tooltip("Instantiates this prefab on a plane at the touch location.")]
GameObject m_PlacedPrefab;
/// <summary>
/// The prefab to instantiate on touch.
/// </summary>
public GameObject placedPrefab
{
get { return m_PlacedPrefab; }
set { m_PlacedPrefab = value; }
}
/// <summary>
/// The object instantiated as a result of a successful raycast
intersection with a plane.
/// </summary>
public GameObject spawnedObject { get; private set; }
void Awake()
{
m_RaycastManager = GetComponent<ARRaycastManager>();
}
bool TryGetTouchPosition(out Vector2 touchPosition)
{
#if UNITY_EDITOR
if (Input.GetMouseButton(0))
{
var mousePosition = Input.mousePosition;
touchPosition = new Vector2(mousePosition.x, mousePosition.y);
return true;
}
else
if (Input.touchCount > 0)
{
touchPosition = Input.GetTouch(0).position;
return true;
}
#endif
touchPosition = default;
return false;
}
void Update()
{
if (!TryGetTouchPosition(out Vector2 touchPosition))
return;
if (m_RaycastManager.Raycast(touchPosition, s_Hits, TrackableType.PlaneWithinPolygon))
{
// Raycast hits are sorted by distance, so the first one
// will be the closest hit.
var hitPose = s_Hits[0].pose;
if (spawnedObject == null)
{
spawnedObject = Instantiate(m_PlacedPrefab,
hitPose.position, hitPose.rotation);
}
else
{
spawnedObject.transform.position = hitPose.position;
}
}
}
static List<ARRaycastHit> s_Hits = new List<ARRaycastHit>();
ARRaycastManager m_RaycastManager;
}
Depending on your comments, if you are placing the object with the button, all you need to do right now is to disable this script that you have attached here. The object should not be moving since what causes its movement is this code bit in Update:
spawnedObject.transform.position = hitPose.position;
You can either comment out this part or deactivate the script, both should work fine.
This is just a simple thing I want to do. I have my cube gameobject rotating and I want to make it so when the camera sees the cube, it stops rotating. If you could steer me in the right direction, I'd appreciate it. thank you
public class cubeMove : MonoBehaviour, MoveObject
{
public Renderer rend;
public void Update () {
rend = GetComponent<Renderer>();
stopWhenSeen();
}
public void move()
{
transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
}
public void stopWhenSeen()
{
if (rend.enabled == false)
{
move();
}
}
}
Implement the OnBecameVisible and OnBecameInvisible MonoBehaviour's message :
private visible = false ;
// OnBecameVisible is called when the renderer became visible by any camera. INCLUDING YOUR EDITOR CAMERA
void OnBecameVisible()
{
visible = true ;
}
// OnBecameInvisible is called when the renderer is no longer visible by any camera. INCLUDING YOUR EDITOR CAMERA
void OnBecameInvisible()
{
visible = false;
}
void Update()
{
if( !visible )
move() ;
}
public void move()
{
transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
}
https://docs.unity3d.com/ScriptReference/Renderer-isVisible.html
You could try the .isVisible bool in your update method.
Here is a thread with other suggestions:
http://answers.unity3d.com/questions/8003/how-can-i-know-if-a-gameobject-is-seen-by-a-partic.html