How to access a script after object has spawned? - networking

In unity multiplayer the player prefab spawns after the scene loads, what is the best way to declare scripts that are needed and avoid the NullReferenceException error?

I'm not that familiar with multiplayer myself, but I believe this could be done through GameObject.Find("") and GetComponent.
I also stumbled across FindObjectOfType. I'm not sure if that's what you're looking for, but it doesn't hurt to post it. Good luck.

Instead of letting a script look for when the prefabs have spawned why not letting the prefabs tell the script it has spawned?
It's really hard to give any kind of example when the use-case is not specified.
Really basic example (and since you're going to use it for networking you might have to redo this a lot so you don't trust the client too much):
class ScriptA : Monobehaviour () {
List<GameObject> prefabs;
public void AddPrefab (GameObject Prefab) {
prefabs.Add (Prefab)
}
}
class Prefab : Monobehaviour () {
void Start () {
FindObjectOfType(ScriptA).AddPrefab(gameObject);
}
}
It's not the best example but the point is, you might need to rethink the architecture

Related

Switching scenes in Unity C# after a short delay without the use of update

Title is self explanatory. I'm trying to switch scenes after a short delay WITHOUT using the update() function. The trigger is a collision between two objects which I have working, I also understand how to switch scenes. It is the delay after the collision which I am struggling with.
I am very new to Unity, any help is greatly appreciated!
Unity supports using Coroutines, which will help with calling the LoadScene function after a delay.
An example of this is as follows:
void OnCollisionEnter()
{
StartCoroutine("LoadLevelWithDelay");
}
IEnumarator LoadLevelWithDelay()
{
yield return new WaitForSeconds(2.0f);
LoadScene(scene);
}
This code isn't fully working since it's just an example, but this is how you could do it. Just create a function of type IEnumerator that waits for however long you want before continuing, and load the scene when it continues.

Why does simple logic crash my arduino code?

I have found that my arduino app will crash if I use the following logic:
if (boolA && boolB) {
doSomething();
}
In a simple program it will work, but with a sufficiently large project, I find I have to change the above to:
if (boolA) {
if (boolB) {
doSomething();
}
}
In a number of projects I have tracked the cause to this logic.
If you want to check memory, you can do so by using Available Memory.
And here I put those files into a library you can use more easily: Avalaible Memory Lib
Although, actual code would be better to try to solve your problem...
You many need to use the long hand syntax like,
if (boolA==HIGH && boolB ==HIGH) {
doSomething();
}
This may also help:
http://forum.arduino.cc/index.php/topic,43588.0.html

Overriding sleep method in Tank battle program

So my class is having a tank battle on Tuesday, and we were each designing logic for a tank. Our teacher designed out API and everything we'll need, and we simply must use what he gave us, however, he encouraged us to "cheat".
There is a sleep method that causes the tank to pause after doing many actions, and I was wondering how I might go about overriding this so it skips or nullifies the sleep.
void sleep(int ns) {
try {
Thread.currentThread().yield();
Thread.currentThread().sleep(ns*100);
Thread.currentThread().yield();
} catch(InterruptedException ie) {
;
}
}
Also, I was considering finding a way that my tank could not die when struck, but I had little success with that as well, there are two methods which affect this aspect of the game, which are checkDead() and kill(): (assuming dead is a boolean with value false)
void checkDead() {
if(dead) throw new Error("Tank "+id+" is Dead");
}
final void kill() {
synchronized(g) {
if(dead)
return;
log("kill()");
dead = true;
logState();
if(g.board[pos.x][pos.y]==this)
g.board[pos.x][pos.y] = null;
}
}
See, I attempted overriding them both with and without the #override, but I'm not sure why it won't hide the superclass's methods. Can anyone give me tips for any one or all of these issues?
Notice the final definition in the method? Assuming you're using Java, you'll find that that is a method that can't be overriden or extended. See Java documentation or Wikipedia for details: http://en.wikipedia.org/wiki/Final_(Java). Show the API that your professor created, and it might explain how damage, death, and states are changed. I'm assuming he has a service-based architecture in terms of recording (and reporting) state changes...
I'm not going to give you suggestions on how to Kobayashi Maru the exercise - it's your philosophy that defines your tactics.
But if I may make one suggestion, consider reading Sun Tzu's The Art of War, especially when attempting to game your opponents or the system.

How Can I make async operations of my own with WinRT using IAsyncOperation interface?

I am developing a metro application and I want to create some async operations whose my own classes would implement.
I have found just examples of async using WinRT operations (e.g. CreateFileAsync). I do not find any intance where someone is creating a async method and consuming it.
Now you can do it. Look at this:
http://blogs.msdn.com/b/nativeconcurrency/archive/2011/10/27/try-it-now-use-ppl-to-produce-windows-8-asynchronous-operations.aspx
http://code.msdn.microsoft.com/Windows-8-Asynchronous-08009a0d
WinRT Async Production using C++
Use create_async in C++:
IAsyncOperationWithProgress<IBuffer^, unsigned int>^ RandomAccessStream::ReadAsync(IBuffer^ buffer, unsigned int count, InputStreamOptions options)
{
if (buffer == nullptr)
throw ref new InvalidArgumentException;
auto taskProvider = [=](progress_reporter<unsigned int> progress, cancellation_token token)
{
return ReadBytesAsync(buffer, count, token, progress, options);
};
return create_async(taskProvider);
}
Use AsyncInfo.Run in .NET:
public IAsyncOperation<IInfo> Async()
{
return AsyncInfo.Run(_ =>
Task.Run<AType>(async () =>
{
return await DoAsync();
})
);
}
I posted the same question in Microsoft forums and they gave me two replies. The first was:
Hi Claudio,
In the Developer Preview there isn't an easy way to create your own
async operations. We are aware of this shortcoming and are trying to
solve it for the next pubic release. In the meanwhile, you could
design your API as async and we will provide guidance on how to
convert sync to async.
Thanks
Raman Sharma, Visual C++
When I asked for the hard way to do this, another guy, someone responsible for PPL said me:
We’re planning to do a refresh of the sample pack we released a few
weeks ago and add a few samples on creation of async operations. I
expect that it will happen in a couple of weeks or so. If you keep an
eye on our blog at http://blogs.msdn.com/b/nativeconcurrency, you’ll
be the first to know.
As to how hard it is... The general-purpose solution that we’re
contemplating is about 1000 lines of C++ code making copious use of
template metaprogramming. Most of it will be in the header file so you
can explore it yourself. While a less general solution can be less
complex, you will still need to implement a base class, do the state
management, error handling etc. At this moment I can’t go into more
detail, but I will say that you will love how easy it is to author
async operations with PPL – so hang in there!
Artur Laksberg PPL team
Then, there is no solution at that time. Thank you all.
Yes, see Ben Kuhn's //BUILD/ talk: http://channel9.msdn.com/events/BUILD/BUILD2011/PLAT-203T He shows how to build an asynchronous API.
At the current time, there is no good solution for high level (C++/WX) classes. However if you use the low level C++ interfaces, you can use the WRL::AsyncBase class to help build your async interfaces.
Here is documentation about the AsyncBase class.
It is confusing, but there is a difference between WinRT C++ code and WRL. You can use WRL to code to the ABI layer directly. WRL does not use exceptions, but loves templates. The recommend coding style for WinRT is not the same as WRL.
I am not sure if everyone can do this, but using WRL you in general need to implement a class that inherits:
class CreateAysncOp: public RuntimeClass<IAsyncOperation<result_runtime_class*>,AsyncBase<IAsyncCompletedHandler<result_runtime_class*>>
{
...
Then you can use
hr = MakeAndInitialize<CreateAsyncOp, IAsyncOperation<type_foo*>>(...);
C++ WinRT is now the best way to implement WinRT async methods. This uses co_await and co_return, new C++ language features (in the process of standardization). Read the docs on this page.

Asynchronous Callback in GWT - why final?

I am developing an application in GWT as my Bachelor's Thesis and I am fairly new to this. I have researched asynchronous callbacks on the internet. What I want to do is this: I want to handle the login of a user and display different data if they are an admin or a plain user.
My call looks like this:
serverCall.isAdmin(new AsyncCallback<Boolean>() {
public void onFailure(Throwable caught) {
//display error
}
public void onSuccess(Boolean admin) {
if (!admin){
//do something
}
else{
//do something else
}
}
});
Now, the code examples I have seen handle the data in the //do something// part directly. We discussed this with the person who is supervising me and I had the idea that I could fire an event upon success and when this event is fired load the page accordingly. Is this a good idea? Or should I stick with loading everything in the inner function? What confuses me about async callbacks is the fact that I can only use final variables inside the onSuccess function so I would rather not handle things in there - insight would be appreciated.
Thanks!
Since the inner-class/ anonymous function it is generated at runtime it needs a static memory reference to the variables it accesses. Putting final to a variable makes its memory address static, putting it to a safe memory region. The same happens if you reference a class field.
Its just standard java why you can only use Final variables inside an inner-class. Here is a great discussion discussing this topic.
When I use the AsyncCallback I do exactly what you suggested, I fire an event though GWT's EventBus. This allows several different parts of my application to respond when a user does log in.

Resources