(31,16): error CS1525: Unexpected symbol `(', expecting `)', `,', `;', `[', or `=' - android

The script I have is for to pause and unpause the gameobject . I have two of the same errors (31,16): error CS1525: Unexpected symbol (', expecting)', ,',;', [', or='
I am just trying to pause and unpause the gameobject . Maybe pause and unpause more in my scene . I need the gameobject pause for a couple of seconds and unpause . Dont what to pause the gameobject by a key. Here is my script :
using UnityEngine;
using System.Collections;
public class star : MonoBehaviour {
GameObject[] pauseObjects;
void Start () {
pauseObjects = GameObject.FindGameObjectsWithTag("Player");
}
void Pause(){
StartCoroutine(waitToUnpause);
}
IENumerator waitToUnpause(){
//do the thing to pause game
Time.timeScale = 7f;//or some other method
yield return new WaitForSeconds(7);///or any duration you want
Time.timeScale = 1f;//or some other method
}
void pauseGameobject()
{
timeLeft -= Time.deltaTime;
if(timeLeft < 0)
gameObject.SetActive(false);
{
start coroutine("wait");
}
}
public ienumenator wait()
{
time.timescale = 0;
yield return new waitforsceonds(7);
time.timesale = 1;
}
void pauseGameobject()
{
if(timerleft < 0)
{
start coroutine("wait");
}
}
public ienumenator wait()
{
time.timescale = 0;
yield return new waitforsceonds(7);
time.timesale = 1;
}
}

This code is compiling without errors (yours is pretty ... unclean). It will definitely not work though. Also I changed some naming to match naming conventions (lower/upper case).
using UnityEngine;
using System.Collections;
public class Star : MonoBehaviour {
GameObject[] pauseObjects;
// I guess this variable is meant to be a field
// it is never set to any initial value!
float timeLeft;
void Start () {
pauseObjects = GameObject.FindGameObjectsWithTag("Player");
}
void Pause(){
StartCoroutine(WaitToUnpause());
}
IEnumerator WaitToUnpause(){
//do the thing to pause game
Time.timeScale = 7f;//or some other method
yield return new WaitForSeconds(7);///or any duration you want
Time.timeScale = 1f;//or some other method
}
void PauseGameobject()
{
timeLeft -= Time.deltaTime;
if(timeLeft < 0)
{
gameObject.SetActive(false);
StartCoroutine(Wait());
}
}
public IEnumerator Wait()
{
Time.timeScale = 0;
yield return new WaitForSeconds(7);
Time.timeScale = 1;
}
// The following code is nearly a duplicate of the above two functions
// void PauseGameobject()
//
// {
//
// if(timeleft < 0)
//
// {
//
// StartCoroutine(Wait());
//
// }
//
// }
//
// public IEnumerator Wait()
//
// {
//
// Time.timeScale = 0;
//
// yield return new WaitForSeconds(7);
//
// Time.timeScale = 1;
//
// }
}

Related

Android Plugin in Unity - No returnvalue

im trying to create an android plugin and import it in unity but i always get 0 as return value from the plugin method and i cant fix this issue.
Here is what i did:
AndroidStudio:
-Created a new project
-Created a library module (package: com.e.timerlibrary)
-Created Public Class "MyPlugin"
-Build -> "Make Module 'timerlibrary'"
-copied "classes.jar" file into "Assets/Plugins/Android" in Unity
MyPlugin only has one method:
public int testmethode(){
return 100;
}
Unity:
AndroidJavaObject JavaTimerClass = new AndroidJavaObject("com.e.timerlibrary.MyPlugin");
TextPlugin.text = JavaTimerClass.Call<int>("testmethode").ToString();
TextPlugin.text should display "100" but its always 0.
It seems like the name of the package cant be found
Hopefully someone can help me. Im new to unity&Androidstudio and followed many tutorials on youtube but i cant fix this issue.
Here is my full c# code. it's basically a timer.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CountDownTimer : MonoBehaviour
{
public float timeValue = 0;
public float timeValuePause = 0;
public float sliderValue;
public Slider slider;
public Text textTimer;
public Text textTimerBtn;
public Text TextPlugin;
bool timerActive = false;
bool backTimerActive = false;
AndroidJavaObject JavaTimerClass = new AndroidJavaObject("com.e.timerlibrary.MyPlugin");
int testvar1;
// Start is called before the first frame update
void Start()
{
textTimer.text = timeValue.ToString();
//startService();
}
// Update is called once per frame
void Update()
{
if (timerActive)
{
timeValue -= Time.deltaTime;
textTimer.text = timeValue.ToString("f0");
slider.value = timeValue;
if (timeValue <= 0)
{
timerActive = false;
textTimerBtn.text = "Start";
timeValue = 0;
slider.interactable = true;
}
}
}
public void OnTimerBtnClick()
{
textTimerBtn.text = timerActive ? "Start" : "Stop";
timerActive = !timerActive;
slider.interactable = false;
if (timerActive==false)
{
timeValue = 0;
textTimer.text = timeValue.ToString("f0");
slider.interactable = true;
slider.value = 0;
}
}
public void GetValueOfSlider(float value)
{
if (timerActive == false)
{
textTimer.text = value.ToString("f0");
timeValue = value;
}
}
void OnApplicationPause(bool pause) //Wird nur jeweils 1 mal ausgeführt!!
{
if (pause)
{
//startService1();
//TextPlugin.text = "pause";
TextPlugin.text = JavaTimerClass.Call<int>("testmethode").ToString();
}
else
{
//TextPlugin.text = "unpause";
stopService1();
}
}
void startService1()
{
/* if (!backTimerActive)
{
JavaTimerClass.Call("StartTimerService");
backTimerActive = true;
} */
TextPlugin.text = JavaTimerClass.Call<int>("testmethode").ToString();
//TextPlugin.text = JavaTimerClass.Call<int>("GetTime").ToString();
}
void stopService1()
{
//TextPlugin.text = JavaTimerClass.Call<int>("StopTimerService").ToString();
backTimerActive = false;
}
}
here is java code:
package com.e.timerlibrary;
public class MyPlugin {
public int testmethode(){
return 100;
}
}
i know it looks pretty bad but im only trying to get the plugin to work

Making multiple GET requests in retrofit2

I have a requirement where I want to make multiple GET requests, what will be best practice in java not using RxJava.
Here I have given parameter as i in getPhotos(), specifies id which loads data in json accordingly. This can run concurrently.
PhotoList list = UnplashClient.getUnplashClient().create(PhotoList.class);
for(int i=0; i<10; i++) {
call = list.getPhotos(i);
call.enqueue(new Callback<List<Photo>>() {
#Override
public void onResponse(Call<List<Photo>> call, Response<List<Photo>> response) {
}
#Override
public void onFailure(Call<List<Photo>> call, Throwable t) {
}
});
If you are looking for serial execution of api calls one after the other, you can make use of Task. This is similar to what Rx java is doing.
Please find the pseudo code below with an example :
private void fetchPhotos() {
Task<Photo> task = null;
List<Photo> photos = new ArrayList<>();
for (int i = 0; i < 10; i++) {
if (task == null) {
task = getPhoto(i);
} else {
final int pos = i;
task = task.onSuccessTask(photo -> {
photos.add(photo);
return getPhoto(pos);
});
}
}
task.addOnCompleteListener((photoTask) -> {
photos.add(photoTask.getResult()); //Adding the final result.
for (int i = 0; i < photos.size(); i++) {
Log.i("DEMO", photos.get(i).toString());
}
});
}
private Task<Photo> getPhoto(int i) {
Task<Photo> task = Tasks.call(Executors.newSingleThreadExecutor() /*You can specify the threading here*/, () -> new Photo(i) /*Your logic to fetch photo goes here...*/);
return task;
}
class Photo {
int pos = 0;
Photo(int p) {
this.pos = p;
}
#Override
public String toString() {
return String.valueOf(pos);
}
}
Running above code, you can see result in sequential order printed in Logcat. Here the chaining of requests happens from the success of previous request.

How to pause and start a Real time line Graph in GraphView when it is running?

I need to pause and start a line graph in the middle while running.I am using GraphView library. My line graph is showing the graph correctly.I need to implement pause and start from the point where it has paused.How to do that?
Thank you in advance..
I have added my code below.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.fhrlistitemgraph);
String data = getIntent().getExtras().getString("data");
GraphView graph = (GraphView) findViewById(R.id.llgraphview);
series = new LineGraphSeries<DataPoint>();
graph.addSeries(series);
// customize a little bit viewport
Viewport viewport = graph.getViewport();
viewport.setYAxisBoundsManual(true);
viewport.setMinY(0);
viewport.setMaxY(200);
//viewport.setYAxisBoundsManual(true);
viewport.setScalable(true);
viewport.setScrollable(true);
}
#Override
protected void onResume() {
super.onResume();
// we're going to simulate real time with thread that append data to the
// graph
new Thread(new Runnable() {
#Override
public void run() {
String value = null;
String[] data = data.replaceAll("\\[", "").replaceAll(" ", "").replaceAll("\\]", "").split(",");
// we add 100 new entries
for (int i = 0; i < data.length; i++) {
final int j;
j=i;
value = data[i];
final String values;
values = value;
runOnUiThread(new Runnable() {
#Override
public void run() {
addEntry(j,values);
}
});
// sleep to slow down the add of entries
try {
Thread.sleep(600);
} catch (InterruptedException e) {
// manage error ...
}
}
}
}).start();
}
private void addEntry(int i,String value) {
// here, we choose to display max 10 points on the viewport and we
// scroll to end
series.appendData(new DataPoint(i, Integer.valueOf(value)), true, 5);
}
If you stop the thread you've stopped even graph, and when you restart the thread also the graph restart to screen data.
You can use a button in UI to stop the thread.
In a my case, i have insert a boolean to stop the update of graph because the thread was not only that but also other calculations they needed, when the value is true the graph is updated when the value is false the graph is stopped. The value of boolean change whe the button in UI is pressed.
boolean updateGraph = true;
if(updateGraph=true){
series.appendData(new DataPoint(countx++, usedramd), true, 60);
}
And with the button you change the value of boolean updateGraph.

How to make checkboxes work in a live wallpaper Android app?

I have three check boxes in my live wallpaper's settings that I need to figure out how to make them work, I want for example checkbox1 to execute code1, checkbox2 to execute code 2 and the last checkbox to execute code3:
code1:
private void incrementCounter() {
if (mImagesArrayIndex >= mImagesArray.length-10) {
mImagesArrayIndex = mImagesArray.length-10;}
if (mImagesArrayIndex <10) {
mImagesArrayIndex = 10;
code2:
private void incrementCounter() {
if (mImagesArrayIndex >= mImagesArray.length-20) {
mImagesArrayIndex = 0;}
if (mImagesArrayIndex <0) {
mImagesArrayIndex = mImagesArray.length-20;
}
}
code3:
mImagesArrayIndex++;
code3 (goes into code1 and code2), codes1,2,3 are all in CustomWallpaper.java That's all, I have already set my settings layout and it looks like this:
solution:
public void run() {
SharedPreferences myPref = PreferenceManager.getDefaultSharedPreferences( CustomWallpaper.this);
try {
while (true) {
drawFrame();
if (myPref.getBoolean("lwp_o_scroll_lock_key",true))
incrementCounter1();
else
incrementCounter2();
if (myPref.getBoolean("lwp_auto_animation_key",true))
mImagesArrayIndex++;
else
//
// if (myPref.getBoolean("lwp_auto_animation_key",true))
//incrementCounter2();
Thread.sleep(SeekBarPreference.mCurrentValue);
}
} catch (Exception e) {
//
}
}

AnimationDrawable Pause ?

Hello I was trying to Pause Animation Drawable but could not succeeded. With the help of stack overflow I atleast got the help of animationDrawable end listener here is the code for it . IS there any possible way where I can pause the animation Drawable and Start it from where it has paused ...
public abstract class CustomAnimationDrawable extends AnimationDrawable{
/** Handles the animation callback. */
Handler mAnimationHandler;
Runnable r= new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
onAnimationFinish();
}
};
public CustomAnimationDrawable(AnimationDrawable aniDrawable) {
/* Add each frame to our animation drawable */
for (int i = 0; i < aniDrawable.getNumberOfFrames(); i++) {
this.addFrame(aniDrawable.getFrame(i), aniDrawable.getDuration(i));
}
}
#Override
public void start() {
super.start();
/*
* Call super.start() to call the base class start animation method.
* Then add a handler to call onAnimationFinish() when the total
* duration for the animation has passed
*/
mAnimationHandler = new Handler();
mAnimationHandler.postDelayed(r, getTotalDuration());
}
/**
* Gets the total duration of all frames.
*
* #return The total duration.
*/
public int getTotalDuration() {
int iDuration = 0;
for (int i = 0; i < this.getNumberOfFrames(); i++) {
iDuration += this.getDuration(i);
}
return iDuration;
}
/**
* Called when the animation finishes.
*/
abstract void onAnimationFinish();
public void destroy()
{
mAnimationHandler.removeCallbacksAndMessages(r);
mAnimationHandler.removeCallbacksAndMessages(null);
}
}
Kindly please help is there any way i can pause ?
I've been looking around, and it doesn't seem that there's a way to directly do it. All of the variables and methods for setting the frame in AnimationDrawable are private. However, you can get the index of the frame the animation is on when you hit pause and then create a new animation by iterating through the original animation from the index of the last frame played (and then start over and add the rest if the animation is cyclical).
I started out with an XML based animation loop, and then just added another one for pause and resume. Here's what I ended up doing, and it's working fine so far, with relevant variables listed first.
private ImageView sphere;
private AnimationDrawable sphereAnimation;
private AnimationDrawable sphereResume;
private AnimationDrawable activeAnimation;
private Drawable currentFrame;
private Drawable checkFrame;
private int frameIndex;
private void pause()
{
looping = false;
sphereResume = new AnimationDrawable();
activeAnimation.stop();
currentFrame = activeAnimation.getCurrent();
frameLoop:
for(int i = 0; i < sphereAnimation.getNumberOfFrames(); i++)
{
checkFrame = activeAnimation.getFrame(i);
if(checkFrame == currentFrame)
{
frameIndex = i;
for(int k = frameIndex; k < activeAnimation.getNumberOfFrames(); k++)
{
Drawable frame = activeAnimation.getFrame(k);
sphereResume.addFrame(frame, 50);
}
for(int k = 0; k < frameIndex; k++)
{
Drawable frame = activeAnimation.getFrame(k);
sphereResume.addFrame(frame, 50);
}
activeAnimation = sphereResume;
sphere.setImageDrawable(activeAnimation);
sphere.invalidate();
break frameLoop;
}
}
}
private void play()
{
looping = false;
activeAnimation.setOneShot(true);
activeAnimation.start();
}
private void stop()
{
looping = false;
activeAnimation.stop();
activeAnimation = sphereAnimation;
sphere.setImageDrawable(activeAnimation);
}
private void loop()
{
looping = true;
stopSoundEffect();
activeAnimation.setOneShot(false);
activeAnimation.start();
}
The method by Zorbert Crenshaw is Nice, but it's complicated.
I have another solution.(Need surround with try/catch because reflection is unsafe).
you can call getCurFrameFromAnimationDrawable to save the current frame before stop Animation, and call setCurFrameToAnimationDrawable to start from any frame.
'30L' should be replaced your param of duration.
private int getCurFrameFromAnimationDrawable(AnimationDrawable drawable){
try {
Field mCurFrame = drawable.getClass().getDeclaredField("mCurFrame");
mCurFrame.setAccessible(true);
return mCurFrame.getInt(drawable);
}catch (Exception ex){
Log.e(AnimTool.class.getName(), "getCurFrameFromAnimationDrawable: Exception");
return 0;
}
}
private void setCurFrameToAnimationDrawable(AnimationDrawable drawable, int curFrame){
try {
Field mCurFrame = drawable.getClass().getDeclaredField("mCurFrame");
mCurFrame.setAccessible(true);
mCurFrame.setInt(drawable, curFrame);
Class[] param = new Class[]{Runnable.class, long.class};
Method method = Drawable.class.getDeclaredMethod("scheduleSelf", param);
method.setAccessible(true);
method.invoke(drawable, drawable, 30L);
}catch (Exception ex){
Log.e(AnimTool.class.getName(), "setCurFrameToAnimationDrawable: Exception");
}
}
This is a late answer to the question. But it might help with the other one. To pause and resume AnimationDrawable, simply customize it and handle with only one variable.
class CustomAnimationDrawable1() : AnimationDrawable() {
private var finished = false
private var animationFinishListener: AnimationFinishListener? = null
private var isPause = false
private var currentFrame = 0
fun setFinishListener(animationFinishListener: AnimationFinishListener?) {
this.animationFinishListener = animationFinishListener
}
interface AnimationFinishListener {
fun onAnimationFinished()
}
override fun selectDrawable(index: Int): Boolean {
val ret = if (isPause) {
super.selectDrawable(currentFrame)
} else {
super.selectDrawable(index)
}
if (!isPause) {
currentFrame = index
if (index == numberOfFrames - 1) {
if (!finished && ret && !isOneShot) {
finished = true
if (animationFinishListener != null) animationFinishListener!!.onAnimationFinished()
}
}
}
return ret
}
fun pause() {
isPause = true
}
fun resume() {
isPause = false
}
}

Categories

Resources