Why is the private int variable in this c# program not updating? - c#

Here's the program:
[SerializeField] ARPointCloudManager mArPointCloudManager;
private int numPointsUpdated = 0;
// Start is called before the first frame update
void Start()
{
UpdateTextPlanes();
mArPointCloudManager.pointCloudsChanged += onPointCloudsChanged;
}
// Update is called once per frame
void Update()
{
UpdateTextPlanes();
}
void onPointCloudsChanged(ARPointCloudChangedEventArgs args)
{
foreach (var pointCloudUpdated in args.updated)
{
numPointsUpdated += 1;
}
}
private void UpdateTextPlanes()
{
PlaneText.SetText(" Point Clouds Updated = " + numPointsUpdated);
}
The values of the private int variable remains zero & i don't understand why it's happening. I tried making the variable static & placing it at the top of my class before everything else but that didn't make any difference. I've searched around a lot but i can't find either solutions or explanations. I'm a beginner.

The problem was resolved when i wired all of the variables correctly in my unity project.

Related

How can i give reward to users on IronSource Rewarded Video?

I have two scenes in my project. There is only one award-winning video for each scene.
In first scene, Everthing is okey, but if you come to second scene to first scene, i can't give reward to users and endofRewarded panel is not visible. What is the correct method for giving reward? How can i do that?
P.s : I know the tutorial is here.
https://developers.ironsrc.com/ironsource-mobile/unity/rewarded-video-integration-unity/
But, I am beginner.
Thank you.
Here is my code for first scene :
public class RewardedMain : MonoBehaviour
{
public string appkey;
public GameObject endofRewarded, anaEkran;
// Start is called before the first frame update
void Start()
{
IronSource.Agent.shouldTrackNetworkState(true);
IronSourceEvents.onRewardedVideoAvailabilityChangedEvent += RewardedVideoAvaibilityChangedEvent;
IronSourceEvents.onRewardedVideoAdClosedEvent += RewardedVideoAdClosedEvent;
IronSourceEvents.onRewardedVideoAdRewardedEvent += RewardedVideoAdRewardedEvent;
//IronSourceEvents.onRewardedVideoAdReadyEvent += OnRewardedVideoAdReady;
}//END START
public void showRewarded()
{
if (IronSource.Agent.isRewardedVideoAvailable())
{
anaEkran.SetActive(false);
IronSource.Agent.showRewardedVideo("MainRewarded");
}
}
void RewardedVideoAdClosedEvent()
{
IronSource.Agent.init(appkey, IronSourceAdUnits.REWARDED_VIDEO);
IronSource.Agent.shouldTrackNetworkState(true);
}
void RewardedVideoAvaibilityChangedEvent(bool available)
{
bool rewardedVideoAvailability = available;
}
void RewardedVideoAdRewardedEvent(IronSourcePlacement ssp)
{
PlayerPrefs.SetInt("totalCoin", PlayerPrefs.GetInt("totalCoin") + 150);
GameObject.Find("GoldNumberText").GetComponent<Text>().text = PlayerPrefs.GetInt("totalCoin").ToString();
SoundManager.Instance.PlayEarnGoldSound();
endofRewarded.SetActive(true);
}
I'm not quite sure what your project looks like, so I'll give some hints as per the information you've given me now.
The problem you're having is that when you get to the second scene, the objects that are hooked up to this mono script will disappear?
If so, add the following code to awake and your GameObject will exist across scenes!
DontDestroyOnLoad(gameObject);

Unity Question: How Can I Switch From One prefab To Another With GetAxis?

I want to bind the up and down arrow keys to cycle through different sprites upon being pressed. If one end is reached, it would loop back to the first sprite. I've tried using the following code:
public class PhaseChanger : MonoBehaviour
{
// saved for efficiency
[SerializeField]
public GameObject prefabMoon0;
[SerializeField]
public GameObject prefabMoon1;
[SerializeField]
public GameObject prefabMoon2;
[SerializeField]
public GameObject prefabMoon3;
[SerializeField]
public GameObject prefabMoon4;
// needed for new phase
GameObject currentPhase;
bool previousFramePhaseChangeInput = false;
/// <summary>
/// Start is called before the first frame update
/// </summary>
void Start()
{
currentPhase = Instantiate<GameObject>(prefabMoon0);
}
/// <summary>
/// Update is called once per frame
/// </summary>
void Update()
{
// change phase on up arrow or down arrow
if (Input.GetAxis("ChangePhase") > 0)
{
// only change phase on first input frame
if (!previousFramePhaseChangeInput)
{
previousFramePhaseChangeInput = true;
// Save current position and destroy current phase
Destroy(currentPhase);
// instantiate next phase
if (currentPhase = prefabMoon0)
{
currentPhase = Instantiate(prefabMoon1);
}
else if (currentPhase = prefabMoon1)
{
currentPhase = Instantiate(prefabMoon2);
}
else if (currentPhase = prefabMoon2)
{
currentPhase = Instantiate(prefabMoon3);
}
else if (currentPhase = prefabMoon3)
{
currentPhase = Instantiate(prefabMoon4);
else
{
// no phase change input
previousFramePhaseChangeInput = false;
}
}
}
}
When I attach the script to my main camera and run it, I'm able to make a single change with the up arrow, and then nothing else happens on subsequent presses.
I feel like I'm really close to making this work, but I also may being doing the whole thing inefficiently. Help would be much appreciated, thanks!
Also: I know I said sprites in my post and am sharing a script that calls on prefabs. I didn't know how to approach this using just the sprites without making a prefab for each. Is it possible to do this without separate prefabs for each sprite?
Problems
First of all you are using assignments
currentPhase = XY
where you should be using
currentPhase == XY
The reason why it still compiles is the implicit conversion operator for UnityEngine.Object -> bool. Basically your assigning equals writing
currentPhase = XY;
if(currentPhase)
It won't work like this either way because you are using Instantiate to create a new clone of a prefab which will of course have a different reference than the original prefab it was cloned from.
So even if your checks where looking like
if(currentPhase == XY)
they will ever be true.
Solution
Instead of checking for reference equality I would rather store all prefabs/instances in an array
public GameObject[] phases;
and then simply have an int index for this array so you can simply move to the next element from the array by increasing the index.
private int currentPhase;
And you can increase it and make it wrap around using e.g.
currentPhase = (currentPhase + 1) % phases.Length;
so it will always grow from 0 up to phases.Length - 1 and then start over from 0 again.
And then I don't know the exact requirements of your use case but I would suggest to rather not all the time use Instantiate and Destroy but rather have already all the objects as instances under your object and just (de)actívate them!
you could do this like e.g.
public GameObject[] phases;
private int currentPhase;
private void Awake ()
{
Init();
}
private void Update ()
{
if (Input.GetAxis("ChangePhase") > 0)
{
if (!previousFramePhaseChangeInput)
{
previousFramePhaseChangeInput = true;
NextPhase();
}
}
else
{
previousFramePhaseChangeInput = false;
}
}
// Disables all phases except the first one and sets the current index to 0
private void Init()
{
for(var i = 1; i < phases.Length; i++)
{
phases[i].SetActive(false);
}
phases[0].SetActive(true);
currentPhase = 0;
}
// Disables the current phase and enables the next one
// wraps around at the end of the array
public void NextPhase()
{
phases[currentPhase].SetActive(false);
// increase the counter and wrap around at the end of the array
currentPhase = (currentPhase + 1) % phases.Length;
phases[currentPhase].SetActive(true);
}
If you still want to Instantiate the objects because having them already in the scene is no option (for whatever reason) you could do it right before calling Init like e.g.
public GameObject[] phasePrefabs;
private GameObject[] phases;
private void Awake ()
{
var amount = phasePrefabs.Length;
phases = new GameObject [amount];
for(var i = 0; i < amount; i++)
{
phases[i] = Instantiate(phasePrefabs[i]);
}
Init();
}
Though as said I would prefer to already have them right away as this is way less error prone ;)

Unity - Particle system - Particle count

Does any know if Unity has a way to count how many particles have been emitted by a particle system? So I could check to see if there has been an emission, like:
public ParticleSystem mySystem;
private int currentParticleCount;
private int lastParticleCount;
void Start () {
lastParticleCount = mySystem.getEmissionCount();
}
void Update () {
currentParticleCount = mySystem.getEmissionCount();
if(currentParticleCount>lastParticleCount) {
DoStuff();
}
lastParticleCount = currentParticleCount;
}
You can use ParticleSystem.particleCount to return the current number of particles. If that's not giving you the proper amount of particles, use the ParticleSystem.GetParticles function since that returns just the current number of alive particles. Below is an example for both of them:
private ParticleSystem ps;
// Use this for initialization
void Start()
{
ps = GetComponent<ParticleSystem>();
}
// Update is called once per frame
void Update()
{
Debug.Log("Particles Count: " + ps.particleCount);
Debug.Log("Particles Alive Count: " + GetAliveParticles());
}
int GetAliveParticles()
{
ParticleSystem.Particle[] particles = new ParticleSystem.Particle[ps.particleCount];
return ps.GetParticles(particles);
}
The exact feature that you are asking for is not build it, BUT:
You can know the current particles displayed by the system, so you can make a counter that acumulates the number, or if you know the "displaying time" you can do the maths.
Knowing the current particles:
ParticleSystem.particleCount https://docs.unity3d.com/ScriptReference/ParticleSystem-particleCount.html

Trying to access instantiated object in 2d array Unity c#. Cant access or change elements?

First time question here.
I'm trying to build a game board like one you would see playing chess. I've made two scripts, one that spawns the board and stores each instantiated tile in a 2d array. And another script that sets the row and column location and onMouseOver prints that location to the console. However this is always print Row = 0 and Col = 0.
I've come to the conclusion that the 2d array is just setting a clone in memory and therefor the stored values I set via calling the function setRC(); are not being being found as the instantiated objects the the Unity scene don't share the memory location.
Anyone have an idea as to how I can fix this?
public class Map : MonoBehaviour {
public static int Row = 7;
public static int Col = 7;
private GameObject[,]boardPiece = new GameObject[Row,Col];
public GameObject prefab;
public GameObject prefab2;
void Start () {
for (int i = 0; i < Row; i++) {
for (int j = 0; j < Col; j++)
{
if(i%2 ==1 && j%2 ==1 || i%2 ==0 && j%2 ==0)
{
boardPiece[i,j] = (GameObject)Instantiate(prefab, new Vector3(i*4.0f,0,j*4.0f),Quaternion.identity);
}else{
boardPiece[i,j] = (GameObject)Instantiate(prefab2, new Vector3(i*4.0f,0,j*4.0f),Quaternion.identity);
}
boardPiece[i,j].GetComponent<BoardPiece>().setRC(i,j);
}
}
}
}
public class BoardPiece : MonoBehaviour {
private int rowPlace;
private int colPlace;
// Use this for initialization
void Start () {
rowPlace = 0;
colPlace = 0;
}
// Update is called once per frame
void Update () {
}
void OnMouseOver(){
string message = "Row: " + rowPlace + " Col: " + colPlace;
print (message);
}
public void setRC(int R, int C)
{
rowPlace = R;
colPlace = C;
print ("set " + rowPlace + "," + colPlace);
}
}
Without a complete code example (difficult or even impractical to provide for Unity3d projects I know, but still...) it is difficult to know for sure what the problem is. However…
While the Start() method is often used in a fashion similar to a constructor, it's important to understand that it's not in fact one. I don't think it's called yet by the time your code is calling the setRC() method on your new object.
This means that the flow of execution is that you first set the row and column values as desired, and then later the BoardPiece.Start() method is called by the Unity3d framework, setting the row and column values back to 0.
Since the rowPlace and colPlace fields are already set to 0 by default when the object is created, I think the best fix is to just remove those two lines from the Start() method altogether. They aren't needed, and I believe they are responsible for the problem you are having.

Texture load using string to int replace issue

The issue according to my debug log is that my ints counts with no problem however the int to string conversion continues to apply to the original value not the updated counter on runtime. (there are some unused private's here for testing) & the frame values are all good.
a screen shot of my debug log: http://c2n.me/39GlfuI - as you can see the counter increases but 'frame' doesn't.
Hopefully this is self explanatory
using UnityEngine;
using System.Collections;
public class imagecycle : MonoBehaviour
{
public string Startingframe;
private string Nextframe;
private int framecomp = 0;
private int frameint;
private int framestep = 1;
private int maxframe = 119;
private string framestring;
// Use this for initialization
void Start ()
{
Nextframe = ("frame_000");
frameint = 20; // currently adding one to this and resetting on update
}
// Update is called once per frame
void Update ()
{
frameint += framestep;
//Converts framestring to int of frameint -updating frame
framestring = frameint.ToString();
Debug.Log (frameint);
// replaces loaded texture recourse with frame string:
Nextframe = Nextframe.Replace ("000", framestring);
// Loads texture into Currentframe:
Texture Currentframe = Resources.Load (Nextframe) as Texture;
// Applies texture:
renderer.material.mainTexture = Currentframe;
Debug.Log (Currentframe);
if (frameint > 119)
{
frameint = 1;
}
}
void LateUpdate()
{
}
}
that is because in first your next frame is "frame_000" so the replace method will replace 000 with 21 as you can see but after that your nextFrame variable is "frame_21" so there is no "000" in your string so your replace method wont do anything so nextFrame will stay at frame_21
Nextframe = Nextframe.Replace ("000", framestring); wont do anything after the first replace because its string doesnt conatins 000
Ah many thanks, so it was my understanding of the replace function that was incorrect, I assumed it would reset to frame_000 on on each update. Many thanks guys.
And yeah i'll try making it more efficient.
Also ,sorry I can't vote up yet; not enough 'rep'.

Categories