#archived-code-advanced
1 messages ยท Page 154 of 1
hm. Looks correct to me, I'm not sure! like I said, maybe start stepping through it or outputting some debug statements to ensure that the vectors start/end where you expect them to
not that i expect this to be the bug, but you're also normalizing the vector then de-normalizing it for the call to DrawRay.. it seems like your code is correct but .. maybe there's an issue there
you could just call DrawRay on Vector3 direction that you calculate in HitTrackerCast()
i found the issue
the lagg came from a Debug.LogError i had implemented
it caused the editor to crash
too many logs
wouldnt have thought that
what exactly do you mean with the numbers?
ah
I already tried that
but the problem with that is
that they can still collide with every other spawned AI except the previous one
but they aren't allowed to collider with any other
ohh wait you meant the other person right?
my fault
Yup was talking to mike ๐
@misty glade
Vector3 direction = (previousPositions[i] - currentPosition);
rather than
Vector3 direction = (currentPosition - previousPositions[i]);
fixed it :omegalul:
ha, weird
I thought that would be literally the same ray
it was drawing the debugrays backwards and keeping the wrong magnitude as a result
it seems like it should still have worked?
heh
Something is still fucked because the rays go through the enemy but no hit is registered, but eh whatever I'll check that tomorrow lol
the first rays don't look like they do?
oh yeah i guess they clip his right arm
are you using the enemy mesh as the collider? you could make an invisible capsule with the collider that's slightly bigger than his body to ensure you get a collision
yo
Application.targetFrameRate If I set this even to just 5 FPS or some low value, my GPU spins like crazy at 100%
I assume that shit is implemented by sending garbage work to the GPU or something
Do you know a way to limit FPS without spinning the GPU to 100%?
It is not implemented via NOP/garbage. If this is in a XR project, the setting will be ignored.
?
Why does my GPU usage go to 100% then
even if target framerate is 5 FPS
I just spin in a while loop now in a script
It makes CPU usage of one core a bit high
but at least no hot GPU
hey guys what up
am building a blockchain game having some mare difficulties might need hands
Is there any way to sample an animation clip at a specific time?
I need the position of a specific child transform at an exact time in the animation
yes I found that function too
but I don't understand what it's really doing
the docs aren't very helpful
it applies the animation clip at t to the go
what does that mean
why do I need a GameObject for this?
ah I found something interesting https://stackoverflow.com/questions/59054384/get-the-position-of-an-animationclip-at-a-given-time-in-unity3d
if you create an array of GameObjects and use Destroy() to delete one of them, what is the value of the element (which previously contained the gameobject)
just wondering
Sorry was running errands, but yeah.
it's not null because i tried if (arr[some number] == null) Debug.Log("hi")
and nothing was printed
its a reference to a now invalid gameobject
ah
source of "GameObject' has been destroyed but you are still trying to access it." errors
Anyone know how to make a seamless portal
Because its going into unity after I'm done with it. It's bit packing
part of a larger compression system I'm writing
I think I fixed it nonetheless
if (BitReadPosition > 32)
if (BitWriteBufferPosition > 32) These seemed to be the issue. Dumb mistake
changed them to >=
depends on what exactly that is
so i followed brackeys smooth portal tutorial and evrything works the way its supposed to except for it doesnt teleport me
im using a different player controller so maybe that's why
in my heirarchy i have a player and a camera that are seperate
sorry, i'm not familiar with brackey's tutorials
anyone have any resources or recommendations for building the enemy AI for a "moba creep" or simple TD-style enemy? I've got pathfinding and "abilities" (e.g. fire bullet, hit scan, heal, etc.) -- where I'm less clear is how to decide when to trigger the abilities, how to make sure the enemy gets close enough, stops, does the ability, repeat in a more general purpose way
I'm currently thinking: move along waypoints till enemy/player detected, then switch to following target until one of the abilities can trigger
again less clear on what happens after the ability triggers and there's some cooldown, etc.
i'd either go with a simple, code-only state machine if the behaviour is really simple... if its not simple maybe a code-only/custom behaviour tree... if designers are involved a visual behaviour tree from the assetstore
yeah, currently using Node Canvas + tasks written by yours truly
i'd basically recommend exactly that
so FSM for waypoint => attack states (plus whatever)
moba creeps aren't really smart so you cant go wrong really, no matter what you do i guess
lol true that
OK talking it through w/ y'all has me thinking I can make the attack state work as follows: "Move to target till ability can activate, stand still and repeat ability till it is out of range, go to step 1"
which hopefully will have them sort of stand and fire till the player retreats or dies
you probably want some sort of aggro range and max kitable distance
and maybe some sort of threat system to make them somewhat difficult to deal with (if this is a multiplayer thing)
both good ideas -- have some sense of aggro thing that I'm still sorting out -- it's single player thankfully ๐
i know you can do case 1, 2, 5, 6
but is it possible to do something like case array
where array is an array of ints?
nvm
I am trying to make a "lead" for my AI when shooting at a moving target in 2D space.
This is a mathematical solution: https://physics.stackexchange.com/questions/652936/in-2d-space-how-to-calculate-the-direction-to-hit-a-moving-projectile-from-a-po
But given how common this should be in games, is anyone aware of a standard solution for this? - Implementing it myself will be complex especially since it doesn't always have a solution.
Googling keeps getting me standard collision detection, not my specific problem of a lead, the only other solution I found being an estimation
No sure if I should ask this in #archived-code-advanced but I just made a shader to do radial cutout for the sprite renderer just like the image component in the UI.
Now the question is, what is the best way to check collision on it? Should I use a polygon collider? Or are there better ways? "the polygon collider does not autogenerate using this"
The game will be similar to super hexagon so I might just check hit direction and do it manually with a circle collider 2d
You can make a custom collider generator if you have the time. Alternatively you can just check the collision direction inside the OnColission methods to see if the collision is in the cut-out part or in the valid part
I'm sure you already know, but just in case : you can find the direction out with a simple vector.dot product
Thanks, I'll try that, I was planning on doing it that way ๐
guys how do i change the rotation something is instated into the game???
Instantiate(bulletPreFab, FirePoint.position + offSet, (0,0,0,1.0));
this doesnt work but
Instantiate(bulletPreFab, FirePoint.position + offSet, FirePoint.rotation);
does? why?
the first one is equal to quaternion.identity though. it's not nonsense
Are you sure? Methinks they accidentally a constructor
ah damn i'm wrong. it would be quaterion.identity. if they had written new Quaternion(0, 0, 0, 1) but they didn't. yeah, that's nonsense code
it's fun just randomly looking at code which i have no idea about
why does unity run coroutines in the physics loop??
it does for me
I tested it:
first FixedUpdate runs
then my Coroutine
then OnTriggerStay
this does not make sense at all
I printed the name of my GameObject as well. It all seems to happen in the order above
dumb question, but are you using WaitForFixedUpdate?
I'm not
it doesn't run "in the physics loop," it runs after Update
have a look at this, should help clarify things: https://docs.unity3d.com/Manual/ExecutionOrder.html
the physics loop just runs before Update
@gentle topaz how to explain the above then?
@long ivy this is where I come from and it says: what I get printed should not happen
I mean... I think we can trust that the debugs they're giving us are accurate. So why is the documentation wrong is the real question.
then everything you said makes perfect sense based on this execution order
Physics doesn't run at the same time as Update, different time signatures and frequency
or wait, you said the TriggerStay happens after the coroutine?
simplified what I have is:```
void FixedUpdate() { Debug.Log("FixedUpdate: " + name); }
void OnTriggerStay { Debug.Log("OnTriggerStay: " + name); }
IEnumerator MyCoroutine { Debug.Log("Coroutine: " + name); yield break; }
I start the coroutine at a random point in time during the program runs
and I get:
FixedUpdate: myGameObject
Coroutine: myGameObject
OnTriggerStay: myGameObject
FixedUpdate and OnTriggerStay should be in sync. You shouldn't get the coroutine between them (again, according to the docs). So... I agree w/ @hollow wing this is not expected behavior.
The coroutine executes the second you run it, and repeats if you have a Wait event depending on what that wait event is - iirc.
So how it repeats depends on what you put in it
And it executes depending on when specifically you started it
(moved up to the rest)
We don't even know if he's using yield null
you get OnTriggerStay twice? or did you mean FixedUpdate
@wooden cedar check the example please - i think it should answer it?
I imagine you would get both twice if either of them run twice?
The example you shared above has no yield in it, and wouldn't execute.
another dumb question. Any chance your logs are set to collapse?
this still looks correct to me. I'm guessing you're starting the coroutine inside OnTriggerX or OnCollisionX
@gentle topaz I don't follow so far
currently the Coroutine is between FixedUpdate and OnTriggerStay
that is the physics loop
yeah I think you're incorrect
That's what I was saying
it runs by calling StartCoroutine(myScript.MyCoroutine()) from elsewhere - in my example in Update of another MB
there is no testing code. I entountered that in my project
Your example is incomplete, and inaccurate. I suspect what you are seeing is exactly what you are executing.
that's a very vague statement. I can't get much information from that
So is your example code
It's missing the yield and execution
Which specifically defines when a debug log prints
So of course we can't help you
You specifically excluded the only relevent info
added one
as in my code the Debug is at the beginning of the coroutine this is still the valid simplification
The only code you originally provided wouldn't compile. Even if it was fixed to compile the coroutine isn't executed anywhere in your example.
I explained you how the coroutine is started
You didn't show where you are starting it. Which when the debug prints.
No you said you run it randomly
And now your wondering why your debugd are inconsistent
he said it runs from Update
I explained in the beginning that it was started at a random point in time during the program, and said also inside Update
/\
This whole convo could have been avoided with the code being complete.
the specifications of my situation were complete, except for the yield break that I forgot
I can't help you much if you didn't read it sorry
hello! i am making a mobile fishing game and you can earn lobsters overtime. i want to be able to earn them while you have the app closed, but there is also the state for android/ios onpause/onresume and focus/pause im really not sure what to do. i just want to continue to earn money while the app is not up. should i calculate the time between closing/opening?
The easy way is to keep track of the last updated calculation sequence at all times. So if the gap is really large, you know they closed or paused it for a significant amount of time.
@gray pulsar @gentle topaz @long ivy @hushed fable thanks for your meaningful input so far
Can we agree that how I described the scenario this should not happen?
And either I made a mistake somewhere or something is different than the docs states?
public class ExecutionTester : MonoBehaviour
{
private bool _hasStartedCoroutine;
private void FixedUpdate() { Debug.Log("FixedUpdate"); }
private void OnTriggerStay(Collider other) { Debug.Log("OnTriggerStay"); }
private void Update()
{
if (!_hasStartedCoroutine)
{
StartCoroutine(ExampleCoroutine());
_hasStartedCoroutine = true;
}
}
private IEnumerator ExampleCoroutine()
{
Debug.Log("Coroutine");
yield break;
}
}
my game was working fine with multiplayer connecting to each other but there was no player syncronisation as it had not been set up but when i do set it up the players no longer move by controlls at all the host of the server just jitters back to the oringal spot but other player wont move
i folllowed this:
https://youtu.be/AZRdwnBJcfg?list=PLhsVv9Uw1WzjI8fEBjBQpTyXNZ6Yp1ZLw&t=1122
yeah, you cant realistically do anything in the background, so calculating the time is the way to go
Download the example project in the tutorial and open it in a seperate Unity instance. Look at how they setup their transforms versus yours. The source is provided to help you troubleshoot.
mm ok, i forget there was a example project tbh
I suspect you just have one set to Islocal on your side that is off
@gentle topaz could you add me as friend if you're interested in discussing this further?
(ofc if we find anything we'd share the results here)
I mean, I think that it is going to always end up exactly as the documentation says
Realized the example code works, but yours doesn't, because you executed it at a funny time - and didn't share the actual code with us?
when you isolate the problem
I mean I'm stuck here and asking for some help
did you ever actually ask for help with anything? you just said "why does this weird interaction happen"
you still havent sent the full code like lloyd said
so we couldnt really help anyway
Also, assuming you are just doing an idle component here - it helps to use timestamps for your caulculations anyway so you don't actually need to run the math side at the full FPS OR can also offload it to a separate thread for performance
I mean I'm uncomfortable with sending my full code if that's not clear
well, yeah that seems to be pretty obvious... but as for the reasoning? I cannot imagine why
@gentle topaz did, what I think, is a really nice thing and actually tested and wrote out the sample code for you. It shows it working, I think you just need to walk through your code and make the fix now.
However, it does raise the question, why they needed to do that for you. I understand being stuck and not wanting to share actual code. But it sounds like something for #archived-code-advanced that would be ideal to have tried on your own first imho.
It's nice they did that. I didn't ask them
I mean one reason could be I don't even have the permission to share that code. just since you said "you can't imagine why"
yeah sure, but it could just be relevant parts, snippits from the actual codebase that demonstrate the problem
you wouldnt need to show the entire script if it's not relevant
This whole conversation and delay didn't need to exist. You could have made an example on your own - and we wouldn't even have had to discuss any of this...
i wanted to dm those to you. The offer still stands, but I can't dm you because you disabled it
But instead you shared non working psudocode, that didn't reflect what you are doing. And someone guessed on what to do to help you and wrote the examples for you.
yes, and I think I will keep it disabled because of reasons lloyd just stated
it's basically like the X Y problem where you sort of ask for help but it's based on some example that is flawed from the beginning, so we are helping you with / discussing Y but X has been wrong the whole time
Hi guys I need help.
I have a script A attached to many GameObjects with same tag, and inside this script there's a coroutine that should be called from another script B.
I managed to get the array of script A in the script B's void Start(), like this:
ScriptA[] _A;
GameObject[] _gbA = GameObject.FindGameObjectsWithTag("A");
_A = new ScriptA[_gbA.Length];
for (int i = 0; i < _gbA.Length; ++i)
{
_A[i] = _gbA[i].GetComponent<ScriptA>();
}
But now how can I call the coroutine from the script A's array now? I tried but it's wrong.
_A[i].StartCoroutine(CoroutineOne());
@wooden cedar please stop it. I don't want to converse with you again you told me for the 3rd time now how "I have to ask my questions" I'm not interested. I came here with a problem/question. It turned out nobody knew a clear answer and I continued with pseudocode because I didn't have much more at hand. I'm not interested in any more of your input. I will ignore it now. Please respect that. thank you
Nvermind I solved it
I stopped replying to you a long time ago :D
there was nothing wrong: I said I have a problem. I described it with pseudo code and if the information is insufficient then the result is that you cannot help me
As a result I can reconsider my style of asking for help. But I didn't make a mistake
you all are very helpful i think im just not understanding exactly what i have to do. are there any resources you could point me towards? i save how many lobster pots they have as well as the price as it goes up each time.
Hello! Has anyone worked with Heathens Steamworks v2 by chance and managed to get a leaderboard working I keep having issues with mine not sending the info to the leaderboard or how to display it
can anyone think of a reason why im getting a nullreferenceexception?
its happening because of this line of code:
if (q < n - 1 && array[q + 1, w] == null)
im just checking to see if the position in that array is null
either q, n, array, or w is null
how would q n or w be null? they are int
How would I have known that? Also, seems like you've narrowed it down, haven't you.
do u play osu btw?
ok and when u say array
u mean like the array itself?
or array[q+1, w]
and it can't be either because i literally drew array[q+1, w] out
it's over here
o yea q and w are both 0 btw
hmm u gave me an idea tho
if those are all ints, the only way that line gives you a nullrefexception is if array is null. ๐คทโโ๏ธ
yea thats strange af lmfao
but then it should give me outofbounds instead
if the array is null?
no... if the array is null it will give null ref
int[] array = null;
array[0]; // null ref exception
array = new int[1];
array[2]; // out of bounds exception
i see
so what if you have someobject[] array = {null, something, something}
and then did array[0]
would that yield null ref
hmmm
wait
i created an array with values for sure
called arr
i then created another array called array
and made array = arr
would that make array null?
you could like... try debugging it? that's not too hard to test
yea but how would i test
if i cant even access
array[q,w]
o shit
hahahaha ur right
dude, you're posting in #archived-code-advanced. these are the kinds of things that a beginning c# tutorial would teach
o mb
so should i keep posting here?
and we type in beginner code?
i solved the issue thanks @gray pulsar
glad you figured it out! Sorry, I didn't mean to ignore your last two questions. I looked away and missed them.
no its g
trying to generate noise with the Mathematrics package but it seems wrong
texture = new Texture2D( size.x, size.y, TextureFormat.RGB24, false, false );
texture.filterMode = FilterMode.Bilinear;
NativeArray<float3> data = ...
for (var x = 0; x < size.x; ++x) {
for (var y = 0; y < size.y; ++y) {
var value = noise.cnoise(new float2(x, y) * scale * 0.01f);
/// < cnoise output is ranged between -1 and +1 , normalize to [0,1] >
data[x + y * size.x] = new float3((value + 1) / 2);
}}
...
texture.SetPixelData( data , 0 );
texture.Apply();
what seems wrong?
its not smooth
too many black spots
that's what Perlin Noise should look like
the cnoise is GLSL textureless classic 2D noise "cnoise", from the Mathematrics / Noise / classicnoise2D.cs source code*
hmmm i think i know what's wrong , used SetPixel and that's what i get
// Inside For ( x ,y ) loop
var v = ( noise.cnoise(new float2(x, y) * scale * 0.01f) + 1 ) / 2;
texture.SetPixel( x, y, new Color( v,v,v ) );
RGB24 is 8 bits per channel
where NativeArray<float3> is 32 bits per channel ( i think )
anyone know how i could make some stars that move, grow and shrink to put inside of an inverted sphere skybox?
thought this was a super small font code dump at first lmao
.....a particle system? I can't think of anything else
I'd probably make a shader for it tbh
Hi. can I ask why should I write my own State Machine for AI when I can use Animator. for example enum with states {IDLE, WALK....} or Interface IState and implement it in different state classes. why should I choose these way instead of animator. what is the benefit?
The animator also can be used like a statemachine, and allows for you to configure it like a truth table.
Rather, it cuts down the amount of bools/switches you need if you are doing some complex animation transitions
Yes. And the question is
why should I not use Animator and use e.g. enums or my own statemachine
Well, it depends how many different animations you have. If you've just a handful then it would be easy enough to just write your own. The animator shines when you start running into scenarios where you don't want your character to perform a certain animation in the air while being hit, while paralyzed, stuff like that.
You can build a system that fits your problem better and may be more efficient to work with.
public class PlayerRotation : MonoBehaviour
{
float zAxis;
public Joystick aimingJoystick;
Vector3 vec;
void Start()
{
}
void Update()
{
zAxis = aimingJoystick.Horizontal;
transform.rotation = Quaternion.Euler(vec);
}
}
how to add rotation for joystick here
for topdown game
Looks to me like carpet
What you're looking for is a particle system.
Though you can achieve it with instantiating a bunch of star object and have some StarManager that does the calculations.
I don't know which one is more performant. But i doubt you'll want to go with the instantiating thing when u can easily set up a particle system
Which brings up a good question ๐ค
Is particle system more efficient than a bunch of sprites?
its so fun looking through this channel and understanding that i dont understand anything
Any chance someone could send me in the direction of some kind of talk/tutorial, specifically in the areas of allows users to give you an assembly (even better if combined with data in general such as XML/Json).
I'm fumbling around with it myself, but I can already see that just on the data-stage this is going to become a nightmare if I don't find some comparison for myself.
Hey @verbal peak! Love the questions about testing. Testing in Unity takes an expert level of programming knowledge to pull off right now. The culture right now just does NOT support it. Most people say that testing Unity projects is a waste of time for numerous different reasons. The game industry has so many human bodies they can throw at manual testing such that I suspect the automated testing tech tree is languishing. Not to mention that in the C/C++ world the testing culture didn't take off like it did for other programming languages (Ruby being the complete opposite IMO). So TLDR; it is an uphill battle. Please join the fight!
In the future the testing culture for the gaming industry will be much more mature and even content creators/influencers will be pushing good testing practices. This is what I believe. But right now, it is up to experts to translate good testing practices from other programming contexts into game and Unity programming. I have book recommendations that I'm trying to arbitrage into my hobby gaming projects.
I'm figuring it out now, myself, and it is difficult. My best hypothesis RN is to write logic in vanilla C# classes, pass in references from Monobehaviors to these vanilla C# classes via their constructors, and then pass in mocks/spies/fakes in from unit tests.
The C++ engine has been built to control C# MonoBehaviour & ScriptableObject lifecycle stuff. It's annoying from a testing perspective since normal constructor based dependency injection (DI) isn't really an option. You can hack it and make it work but ugh. IMO, its best to treat Monobehaviours and ScriptableObjects as humble objects (humble object pattern), and delegate actual computation to the C# classes. I consider it an integration test when you plug a C# class into a MB or SO.
Warning: oh my god is it difficult, too, because it is so easy to get lost in the vanilla C# world and forget about how that world will interact with the Unity world.
The books I'm using to arbitrage good testing practices into my Unity projects:
- Unit Testing: Principles, practices, and patterns (omg, eye opening!)
- Growing Object-Oriented Software Guided by Tests
- Dependency Injection: Principles, practices, and patterns
Even with these books there is a HUGE amount of synthesis that is required to apply it to a Unity context. I can't even capture all the nuances and complexities in a short discord message. Needless to say; this is an area that could use so many more eyes and so much more expert digestion. The value proposition of automated testing is immense, and even more so for small indie teams. I assert that the teams who develop automated testing as a core competency will move faster than the teams stuck in manual test land, even with test bed scenes.
I'm flagging this as important work for those passionate in the community. Gondor is requesting aid -- will you mount on your Rohan horse and help fight the good fight?
Thanks for the thoughtful response!
Thanks for asking about automated testing! It's something that I'm pretty passionate about
I think there is a lot of influence and money to be gained for whoever does transcribe all of those canon texts and practices and contextualizes them into a clear and cohesive resource on testing within Unity
There is simply nothing out there. It only takes one specialist to write a good manifesto / textbook on it to change the entire industry
Hmmmm I hope so but due to the volatility of Unity and lack of mature testing gurus within our industry, I think anyone who could actually write such a resource is busy with delivering on their job. Will need some time before anyone has done it long enough, and for any best practices to have been proven
I've thought about this a lot
I think the games industry is actually more mature than we think with automated testing
I suspect NDAs prevent the testing gurus in the industry from talking about it publicly
There just seems to be a lot going against getting us to that automated testing future. I hope someone much smarter stumbles upon this conversation and can deliver on this need we're describing. ๐ค
Gotta wait for people to make their money and start retiring so they can write freely about it ๐
Professional Unity development has really only been around for like 5-10 years imo, because old practices get deprecated so quickly with how often Unity makes dramatic shifts
Itโs why Iโm pretty skeptical about anyone actually writing something like this actively
Hi,
I'm working on a walll climbing script, but I'm not sure how to deal with it when working with corners like this.
any idea what is the best approach for it?
I wanted to make raycast on the hands and feets and look around the corner
and place the feet and hands with animated rigging to the other wall and rotate the player
but even then it will bring a lot of challenges
I wonder if there is a more easy way to do it
Maybe? As I've grown as a programmer I've started to notice underlying patterns that don't really change a bunch, even when the runtime context (e.g. Unity) is changing. Maybe it is just wishful thinking on my part. Still; you and I see the value that automated testing can bring to a software project. If we can see it, many others can as well. That's partly why I suspect someone is working on this hard problem.
@regal olive From my experiences working for many many years on large engines (not Unity) and on games: Unit testing is used pretty extensively in engine development (possibly not as much as it could be, but still a lot). But it's not used much in the development of games themselves, primarily because early testing is a cost that has to be balanced against its benefits. If a unit of code is used a thousand times in different contexts by different developers then early, low-level testing is a huge win. If it's used once for one game feature and will be thrown away after the project ends it makes far more business sense to test that one feature with manual functional testing. The large majority of games code is written as the latter type (even if it later evolves into the former type).
So in the context of Unity, the question is: Is Unity a framework for building reusable code on? Or is it a framework for making games as quickly as possible? Obviously the answer is both, but in the sense of whom it is most designed for and what kind of developer it is trying to attract, it seems to me the latter use case heavily dominates.
I appreciate the perspective! I humbly, respectfully disagree. In the "Unit Testing" book I mention above, it provides a way of looking at code and triaging when something is worth testing and when it is not. Understanding when and how testing is providing value is a key skill and one I often seen misunderstood by beginners naive testers.
If a unit of code is used a thousand times in different contexts by different developers then early, low-level testing is a huge win.
I think you are overstating how far reaching a piece of code has to be in order for testing to be worth it. Furthermore; testing has a huge impact on the design of code, so testing early will produce different production code than if there were no automated tests.
If it's used once for one game feature and will be thrown away after the project ends it makes far more business sense to test that one feature with manual functional testing.
This might be right but it is dependent on the specifics of the circumstance. If that one feature is mission critical to the software then having a test on it is typically a good idea. If it is trivial, then obviously having even a manual test might be overkill. Most features will fall somewhere on this spectrum. In the event of a manual test one will have to calculate how much of someone's time will be used up as the project evolves to guarantee that software behavior behaves as expected. It's a trade off. I follow the beyonce rule for features; "if you liked it then you should have put a CI test on it."
So in the context of Unity, the question is: Is Unity a framework for building reusable code on? Or is it a framework for making games as quickly as possible?
I think this is the wrong question. Software is software; be it in the Unity context or another runtime. It's not a matter of if you are building something reusuable. It's a matter of proving to yourself that your software behaves as you expect. Those skilled at testing typically move faster.
There's a ghost hunting unity game where you gather all kinds of evidence in order to find out the type of ghost.
I'm working on a mobile app that would help you figure out what to do to get other evidence judging by what evidence you already gathered.
I'd like to also make a windows app that would create an overlay over the actual game which will provide the info needed.
Would that be possible by making some sort of mod for the game? How would you guys approach this idea?
Iโm going to disagree on that. Iโve worked on 400+ Unity projects, Iโve never once seen a Unit test (even in automated build testing workflows) be worth its implementation. Iโve actually never once seen a Unit test discover an actual bug, just bugs in Unit tests themselves. Maybe itโs helpful if the company is full of new developers or a large project - but they really are just a make work project in Unity (but so is CI in general). Most companies making a game are manually building it every 2 weeks when things are stable - so the 50 adhoc builds by the build pipeline donโt even get used. Itโs just a pointless exercise imo.
There are some rare exceptions, like maybe 2 out of the 400, where it may be helpful (usually where we had 20+ folks on something). But even thenโฆ. The value is questionable at best
Now, backend / web service - yes. That makes sense. But a game or VR experience is more like modern multimedia - you often complete it in a few months as most, publish it, and never touch it again until you need to add a new expansion. It isnโt something you should really be working on for 40+ years.
And the engines and frameworks change too quickly to really get meaningful value out of unit testing them. It just becomes a make work project for short duration things.
But again, thatโs just my opinion. I did start all shiny eyed, adding my nunit, doxygen, build pipelines into every project at the beginning. And had that same perspective back then. I just see it different now.
I donโt complain when we hire a new grad, and they get excited, and work to get unit tests and build pipelines going - because hey they are excited and it keeps them busy for a bit. But Iโm honesty, thatโs just how I feel about it and why.
I am massively interested in this type of response, not going to lie. I find this line of thought very different than what I am used to. My day job is a software engineer working with many different type of testing. Leaning so hard in the other direction is justโฆ so different
I do think if there is an external dependency (i.e. web service) it absolutely makes sense though - because thatโs an error you donโt have the ability to predict and a unit test can discover something
I also should add I am very open to retrying it though. We have more interns than usual right now and my hair is going gray fast
It sounds like you havenโt been exposed to real value being generated from a testing suite for the unity projects you have been a part of. I think this is a part of the problem; Iโm sure most people are in that boat. It is absolutely logical to conclude that it isnโt time well spent given that fact.
Fascinating stuff!
Perhaps interestingly, in the use of unit testing on (non-Unity) games that I've seen, I'd say that the main benefit I've seen from unit testing has not been from the testing itself (which often has relatively weak returns, for many of the reasons lloyd lists), but from its function as documentation. A unit test is an unambiguous (though not necessarily clear) description of the behaviour of a unit of code, that is always known to be up to date - thereby solving two of the commonest problems with documentation of rapidly changing code.
But even then, you come back to questions like "what is the business value of high quality documentation of this code? How many people does the knowledge need to be transferred between? How long does it need to been maintained for? Are there cheaper ways of distributing the knowledge that have similar benefits?" And again, that varies heavily depending on the type of code.
I disagree fundamentally (but respectfullyโ thank you all for your thoughts!). I suspect I represent the rebellious disruptive thought that will prove itself in the very near future. The games industry has this legacy orthodox thought/resistance against automated testing. The software industry elsewhere has up leveled and matured on automated testing; creating games has gotten easier to get in to. The more time passes the more likely this aspect of the games industry will be massively disrupted.
These are my beliefs. I suppose we will see who is right ๐
In my 14 years of game developmemt I have not found unit testing and auto QA to be useful for game development at all. How do you even unit test a player getting stuck in a level? You can beat a good old qualifid QA tester that makes a decent report. I mean sure I can write a test that makes sure that my item generation code generates items and their damage values are within spec but that is the easy part of game dev.
More power to you! But you should be aware that this argument isn't new; I've watched and participated (on both sides) in discussions with essentially these arguments for twenty years, and I'm sure they were going on for almost as many years before that. It's certainly not a settled question, but nor is it one that has been ignored - for people working at low levels in the industry it is rarely out of their consciousness, and there are no clear answers.
(Just to be extra clear, by "low level" I mean low level in the development stack sense, not low level in seniority terms.)
It is enlightening to see these thoughts. One takeaway I have is that the value proposition of automated testing has to be clearly communicated and demonstrated in the gaming/unity software context before people trust it enough to take a deep dive.
There's a ghost hunting unity game where you gather all kinds of evidence in order to find out the type of ghost.
I'm working on a mobile app that would help you figure out what to do to get other evidence judging by what evidence you already gathered.
I'd like to also make a windows app that would create an overlay over the actual game which will provide the info needed.
Would that be possible by making some sort of mod for the game? How would you guys approach this idea?
//Repost, still looking for an answer
I probably wouldnโt do this. You can access windows frame information / memory hacks. Iโm not sure why you would force create a mod for it if it doesnโt already support a mod interface. But you should be able to access the memory and literally just read what items are outstanding etc if you want to build a game trainer
Thatโs how I did my diablo 2 hacking back in the day, just read the memory values
I assume you are talking about Phasmophobia. Even though it's made with Unity, I'm pretty sure you won't be able to do this in unity. You'll need to hook into the running game and put your overlay over it. https://www.youtube.com/watch?v=BIZyxja3Qls something like this
We create an External Overlay by first creating a transparent window which matches the game window and then draw onto it.
Support the channel:
Music: Jay Hifive - Revival
Code: https://github.com/CasualCoder91/ExternalOverlay
Community Discord: htt...
I will say, I think Unreal - Unit testing would be a lot easier to get a return on effort. It has a more rigid structure for game managers etc, and with blueprints it is very โtestableโ. The biggest barrier for Unity with unit testing, imho, is that it is such a big free for all that reusable test scripts just isnโt possible. With Unreal, you could reuse the same test scripts on many peoples projects quite easily. For example, almost everyone uses the same input pattern with Unreal, where you need to actually create the input systems and code them in Unity - which makes it less predictable for reusable Unit tests between projects. That said though, Unreal folks usually donโt worry about learning coding nearly as much.
With Unity, every team and company has different patterns and processes - making unit tests a rewrite between companies and individuals. Tying a unit test into character animations for example, is going to need to be done manually per project. So it just greatly increases the effort - which people are unlikely to do for a 3 month turn around or even a 1 year project where the unit tests canโt be applied to the next project.
The other thing is that Unit tests are really mostly used for utility classes (conversions and what not) which is already handled and unit tested by Unity itself. So where unit tests really shine they arenโt as needed in Unity itself.
The bigger thing to me though is I expect dependency on coding in general to keep wearing down. I expect 10 years from now it would be more rare to code anything for a game - itโll likely be primarily visual programming. In which case unit tests would be built in by the game engine manufacturer not users.
The mod won't actually read information from the game because it would be kinda cheating. The user would find stuff in-game, then check them inside the mobile app which would be connected to the overlay that would show 'Oh, because you found this, only these ghost types are possible now'.
For example a wall drawing made by the ghost. If I make the mod automatically see it and check it in the evidence book, it would be cheating. Instead, the player has to find it and my app would just make his job easier by saying 'these types of ghosts can't do any wall drawings so you're left with this, check this thing to see if it's this ghost, if it does this then it's this ghost and so on'
So I would basically just need to sync the player's mobile app to an overlay just like Discord, Steam or Teamspeak has over the game. @wispy lion
I don't want to read game information, I just want to know how I can place an overlay over their screen (like Discord does) and sync it with the mobile app so when they check a field in the app, the info appears on the overlay
Well, sync is via web sockets or a backend service, the overlay just use the Windows low level functions
I probably wouldnโt use Unity for that though
Not planning on using Unity, just thought there may be some way I can make it a mod instead of telling players 'yeah bro just trust me and install this program'
That would be a question to ask the game creators in that case
It definitely wouldnโt be #archived-code-advanced for Unity
Game of that size definitely has some sort of modding community, so I would seek those out instead
The game is pretty big but unforunately there really are no mods for it, I don't know the reason
Hey, I'm also trying to recreate a free climbing system like yours, After a lot of research I came across a spider controller and thought: the creator must have addressed this problem too. And so, basically, he used two sphere casts, one pointed straight at the wall and one pointed to the moving direction, just check the second one before, otherwise check for the wall (but in fact the second one is useful only if you allow your player to climb on uneven walls)
300k+ reviews on steam, couple tens of thousands of players daily (or monthly?) and still no modding,
Regardless, this is the wrong place to ask about that
Thanks, I think I saw the spider in the list on youtube when searching for climbing tutorials.
I found also other ones, but they are also using other 3rd party plugins that I want to avoid, specially because I'm not sure how it will integrate with Photon and to have full control over it.
Will check that spider video
Understood, only reason I sent it here was regarding the modding part, thank you
yeah there is also project files with it:
https://unitylist.com/p/w9c/Unity-Procedural-IK-Wall-Walking-Spider
Thanks, will compare it with what I was doing, maybe his approach is a better one
my game controls was working fine and clients would connect but i had no yet synced up the movement i added 'photon transform view' and now its just doing this but if i remove it it works fine but the movement isnt synced bettween clients
Hmm this scenario is missing a crucial fact. Is there already coverage preexisting between companies? If so, there isnโt a need to rewrite unless you see an opportunity to improve automated test value (there is always something!). If the test doesnโt exist then it needs to, even if a previous company already wrote a similar test.
Another crucial piece is the concept of the testing suite per project. If there is high value in adding a test to assert software behavior and that test is missing from the project, it is time to write that automated test. Given time is very scare, it is critical that programmers know how to identify high value tests for the project requirements, and to have the practice to not serve as a hinderance.
That's not how I'd look at it. If everyone, at every company, needs to build unique Unit Tests the effort greatly expands. If all the companies are conforming because of the engine, then all companies can reuse the same tests.
The reason the ROI is so bad, is because it is being made per project or per company repeated at tens of thousands of companies.
Simplify and unify the process and the ROI increases 10,000 fold
Definitely donโt test the library code. Test how your software is doing something meaningful (observable side effect) for its users. Thatโs your app code. Donโt test the lib stuff ๐
I'll let the topic go, I don't think you understand what I'm saying with this.
By the way, I really want to say thank you for this discussion. I am really enjoying the intellectual discourse, and I hope others are enjoying this too. Thanks!
I also, to be clear, hold that to myself for not explaining well
I appreciate the feedback. Honestly, I just got done with a swim and I was thinking about our conversation
I do notice how we are approaching it from two different foundational perspectives
Your way is emphasizing time to product delivery
My way is emphasizing software correctness
I'm also probably not the best person for the subject - we've migrated about 60% (thankfully) of our projects to Unreal. And we work on about 8 to 10 VR simulations a month. So we live in more of a multimedia heavy space at our company
Both ways have pros and cons. Big trade offs in general
Does ScreenCapture.CaptureScreenshot copy the screenshot to the clipboard?
if not, is there a way to screenshot the screen then copy the resulting screenshot to the clipboard?
No, you would need to write something that stores a base64 to the clipboard
Or use this, Google is your best friend :)
actually didn't think something like this would be on google lol
I'm not sure if base64 would even still do it these days, so I'd definitely use existing APIs
so I'd have to use an external source to get this to work and not default unity/c# code?
The code to glue ScreenCapture.CaptureScreenshot shouldnโt be too difficult to write.
That call writes to a file. You will have to read that file into the system clipboard. That should be supported in just Unity
It looks like it should work with just those two commands in the forum. This person was troubleshooting why they weren't working for them and other folks said it works fine.
If something is inviting you to download and install a library, I say that is overkill for your use case
System.Drawing.Imageย tempImageย =ย System.Drawing.Image.FromStream(stream);
System.Windows.Forms.Clipboard.SetImage(tempImage);
I'd give those two lines a test first
Maybe an easy win :)
Did someone help you?
no
Can you showcase the player script?
sure 1 sec
im just reopening unity as i had to restart my pc for a update
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using System.IO;
public class PlayerManager : MonoBehaviour
{
PhotonView PV;
void Awake()
{
PV =GetComponent<PhotonView>();
}
void Start()
{
if (PV.IsMine)
{
CreateController();
}
}
void CreateController()
{
Debug.Log("Started Controller");
PhotonNetwork.Instantiate(Path.Combine("PhotonPrefabs", "PlayerController"), Vector3.zero, Quaternion.identity);
}
}
thats player manager
@frigid elbow should i send the player controller too?
Yes the Player Controller please.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class PlayerController : MonoBehaviour
{
[SerializeField] GameObject cameraHolder;
[SerializeField] float mouseSensitivity, sprintSpeed, walkSpeed, jumpForce, smoothTime;
float verticalLookRotation;
bool grounded;
Vector3 smoothMoveVelocity;
Vector3 moveAmount;
Rigidbody rb;
PhotonView PV;
void Awake()
{
rb = GetComponent<Rigidbody>();
PV = GetComponent<PhotonView>();
}
void Start()
{
if (PV.IsMine)
{
Destroy(GetComponentInChildren<Camera>().gameObject);
}
}
private void Update()
{
if (PV.IsMine)
return;
Look();
Move();
Jump();
}
void Look()
{
transform.Rotate(Vector3.up * Input.GetAxisRaw("Mouse X") * mouseSensitivity);
verticalLookRotation += Input.GetAxisRaw("Mouse Y") * mouseSensitivity;
verticalLookRotation = Mathf.Clamp(verticalLookRotation, -90f, 90f);
cameraHolder.transform.localEulerAngles = Vector3.left * verticalLookRotation;
}
void Move()
{
Vector3 moveDir = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;
moveAmount = Vector3.SmoothDamp(moveAmount, moveDir * (Input.GetKey(KeyCode.LeftShift) ? sprintSpeed : walkSpeed), ref smoothMoveVelocity, smoothTime);
}
void Jump()
{
if (Input.GetKeyDown(KeyCode.Space) && grounded == true)
{
rb.AddForce(transform.up * jumpForce);
}
}
public void SetGroundedState(bool _grounded)
{
grounded = _grounded;
}
void FixedUpdate()
{
rb.MovePosition(rb.position + transform.TransformDirection(moveAmount) * Time.fixedDeltaTime);
}
}
First question, do you have a "Photon View" on the Player/Script?
btw, what happens if you make the PhotonView PV to public PhotonView PV and then set the PhotonView in the inspector?
ill try that now
made no diffrence
On Photon View component try to change the Sync choice.
It's on Unreliable On Change
mm ok
yea
Does manual exists?
it does the same
Okay
i tried that already
What happens if you delete the Photon Transform View?
And use the old one?
There's two of them
One with more options..
Oh okay
And everything you do in the prefab is saved?
So when the script spawns the player it's the real prefab and not an prefab from the scene right?
Cause if it is from the scene you need to Override
room manager has its own script
player manager is only on the player manager prefab
using old one gives same result
But the player spawns in via the PlayerManager script?
But what triggers the PlayerManager?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
using UnityEngine.SceneManagement;
using System.IO;
public class RoomManager : MonoBehaviourPunCallbacks
{
public static RoomManager Instance;
void Awake()
{
if(Instance)
{
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
Instance = this;
}
public override void OnEnable()
{
base.OnEnable();
SceneManager.sceneLoaded += OnSceneLoaded;
}
public override void OnDisable()
{
base.OnDisable();
SceneManager.sceneLoaded -= OnSceneLoaded;
}
void OnSceneLoaded(Scene scene, LoadSceneMode loadSceneMode)
{
if(scene.buildIndex == 1)
{
PhotonNetwork.Instantiate(Path.Combine("PhotonPrefabs", "PlayerManager"), Vector3.zero, Quaternion.identity);
}
}
}
thats the room manager it triggers the player manager
Okay..
What is the diffrence between PlayerControll & PlayerController?
its the same
i was redoingn it to see if i messed up
but they give the same result
i could delete PlayerControll as it does nothing
Can you show me a picture of PlayerController prefab?
Play the game again with the other player (2 Players in the lobby)
And then show me one of the players PlayerController GameObject/Prefab in the scene.
The Photon Transform View is still like in the prefab? (When not playing)
im not sure what you mean..?
do you want me to send a pic of the prefab when its not running
Well, that should sync?!
thats what i thought....
If you move you change the PlayerController gameobject transform right?
So you are syncing the right object
yea
if i disable the Photon Transform View it moves the players around fine but they do not sync but with it enabled the players cannot move and the rotation just moves back to the same spot
this just isnt making sense to me, it should be working
This is not making sense for me either..
i could send you the entire project file?
its 180mb so ill compress it and upload it to something like mega
hum idk how to say it in english
it's a versionning tool
source control basically
if you need to share your project at any time, just one git(hub/lab or other) link and that's all
nobody wants to download a 180mb file on its computer coming from a non trustable source
fair enough
Github or Gitlab is a good Version control system.
Does the guy have support/discord? He may help, or he's community
I've used but i would go with GitHub.
yup github is a good one
he does but its not active and i got no respences there
im seting up a github thingy atm
you can use this gitignore https://github.com/github/gitignore/blob/main/Unity.gitignore in your project to avoid sending useless files
basically tells to git what needs to be uploaded, and what shouldn't
alright
sorry if im a bit slow but i gotta download github desktop and my wifi is quite slow and i havnt done this before
im folowing a tutorial
no no dw
tbh not a lot of people would have started using git
i'm used to people who don't really listen to advices x)
so nice! ๐
oh ok ๐
i think ill just keep updating the project to git so if i run into any more issues i cant solve then its easier to find help
yup that's the right thing to do:D
is github usually this slow...
no ๐
you just have a bad connection :/
@frigid elbow heres the repo
https://github.com/Skutela32/FPS-Game
anyone else wanting to try solve this please dm me, the players do not move when trying to sync up, i have a github file of the project so you could download it and try to solve it
hi, this is just a question, how much servers allow free photon license?
Contact Photon/Exit Games.
Photon is sort of a blanket term, there are many Photon products. Pretty sure pricing is on their website
(im not actually sure if this is considered "advanced" or just a general problem) Im working on a file browser to select images at runtime - everything works fine except when navigating to large directories (100+ images), it stall the main thread, im wondering if theres a good approach for this? Should I "page" the contents to maybe 30 images per page or something? Is it possible to "progressively load" the images on a background thread? By calling Texture2D.Create, thats a Unity call so I have a feeling itll tell me it can only be done on the main thread, is there a common work-around for this? Would a "Task" be able to help me here? I plan to cache everything into a Hashset or Hashtable later so I dont have to re-create the images when changing directories, but initially is there a way to cut down the loading time of "large directories"? Right now when you navigate to a directory, I filter only the image files and run a loop to create and display them on some scrollview - the main thing is, id like it to simulate Windows where you can see a grid view preview of each image along with its file name so you know what your selecting before you confirm it
how big are said images? (resolution? format? etc)
I guess it depends on the user, they could be small images they could be 4K images, it basically lets them navigate anywhere on their computer with System.IO.GetFiles/System.IO.GetDirectories, filtered by image file extensions - so "unknown" I guess? (though mainly im only looking at PNG, JPEG/JPG, BMP)
are you using this to load the images or are you reading them in as raw bytes?
Using this class significantly reduces memory reallocation compared to downloading raw bytes and creating a texture manually in script. In addition, texture conversion will be performed on a worker thread.
Huh, I can try it - all the files are local and not on the web, but I assume this would also work for local files
file:///, yea
TL;DR its just a generically optimized image loader solution
for basic stuff. if you need more than that, you'll probably want to look towards the FreeImage API
you can also always convert image data in a background thread to GPU-ready data and just pass pointers back and forth
Interesting, ill give this a try and see if it helps, for now I really only need just basic PNG/JPG loading mostly to help our designers test certain textures in-game before they finalize designs, so im sure if I just ask them to always save in either format, and this works, then that should be good for what I need - though if this might not work out, how might I do the background thread? Is that a Task or some other API?
if using FreeImage I'd just do it myself with C# threads.
anything that doesn't touch the main worker
Interesting, cause Texture2D is a Unity-specific class, so I assume that has to be done on the main thread to get it, though I might have to look into it more
It seems to still take a bit of time but nowhere near as long, with a like 5 - 7 second "please wait..." honestly I can probably get this to do what I need it - thanks so much for showing me this!
Hey, we are trying to use the IBM unity sdk and Unity sdk core and have been working on speech to text ExampleStreaming, we are not able to get the ant output form it, any Idea why could this be an issue?
hey i have issue with photon network
when i join game i can move and rotate
but if someone joins game i cant move or do anything
and how to add here thing so if player leave the camera will stay in same pleyes
oh. wrong
wrong chat i should on #archived-code-general
sr
oh
I've a problem with sorting layers. How can I solve this: platforms < player < water but also platforms> water
< means higher sorting layer
how about water < platforms < player
public Sprite GetPrefabPreview(string path) { GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path); var editor = Editor.CreateEditor(prefab); Texture2D tex = editor.RenderStaticPreview(path, null, 1000, 1000); Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(tex.width / 2, tex.height / 2)); DestroyImmediate(editor); return sprite; }
causes this error
hey there, I'm having a problem with my neuronal network AIs (which should learn to walk) just keep doing this and not moving (as it seems) the legs
also, how can I make that they need to balance themselves so they don't fall over; currently they can balance themselves by just standing there
anyone here with experience in quaternions?
only slightly and depends on the use case
i need to rotate something 180 on y and 180 on z. Practically mirror both axes
instantly
ah
I think you don't even need to use Quaternions for that
you could just use transform.eulerAngles I think
yea thats whats im reading now but i tried it and guess what
which works in Vector3
i get -180 on x
GameObject.Find("Left").transform.eulerAngles = new Vector3(0, 180, 180);
maybe because euler is world?
and the gameobject is the child of another one
since the rotation is written in local space in the editor
is there a local version?
still -180 on x
if you would like to write it completely yourself you could also add the euler angles to the euler angles of all the parents
hmm
wait I will try myself
the object is not a child btw
k
when i rotate it in the editor it works, via script it doesnt
Unity stores rotations as quaternions
Using euler angles in this way in your code is just asking for trouble
they're basically just for convenience in the editor
docs literally say use euler not quaternion lol
what docs
Which part?
yeah
Full stop. Do not directly manipulate Quaternions. Use the helper functions ie: AngleAxis, FromToRotation, Quaternion.Euler
I tried that too
If you want to rotate on two axes at once it's usually best to create a parent pivot object.
outputs though negative as well
do not read euler angle outputs from the Transform they are not unique and not very friendly to script with
-180 and +180 are the same and it's a crapshoot which one you get back
can make sure it's positive, can convert it
well
When did they turn "Generalist" tags blue? O.o
but what's the reason for it
IDK >_> probably to avoid confusion with mods?
The issue is that Euler angles aren't unique. Rotation of (0, 180, 180) is exactly equivalent to (-180, 0, 0)
huh last time i checked they were orange
ah yeah mods are also orange
makes sense
ah yeah that's why
Quaternion.Euler gives -180 on x
and 720 will be converted to 0 right so you can't rotate by 720 degrees on time?
you need to learn how to use Quaternion.Euler first, reading up some basic documentation should be enough
Your problem is that you're reelying on reading back the euler angles from the Transform and acting on them. Just don't do that and you won't have problems
@regal olive lets head on over to #๐ปโcode-beginner . Explain what you're trying to do
You can, but it ends up in the same place so what do you expect to see?
I mean rotating in time
of course it's the same endrotation
but it also wouldn't rotate at all right?
No problem there
if you add e.g. 1 degree every frame it'll rotate just fine up to 720 degrees
100% irrelevant
the only gotcha is that if you try for example transform.eulerAngles.x >= 720 to check when to stop the rotation it'll never reach that
Whats the proper way of stopping a coroutine using MEC?
I ended up doing .CancelWith(gameObject) otherwise it errors out when switching scenes and I have the coroutines still running
I've a problem with sorting layers. How can I solve this: platforms < player < water but also platforms> water
< means higher sorting layer
but water should be higher than player
It sounds like you want
platforms > water
and also
water > platforms
which doesn't make sense
I make a 2.5D game
maybe draw a picture of what you want
and the platforms should be higher than the water
In the appropriate channel
ok
hello! i am making a mobile fishing game and you can earn lobsters overtime. i want to be able to earn them while you have the app closed, but there is also the state for android/ios onpause/onresume and focus/pause im really not sure what to do. i just want to continue to earn money while the app is not up. should i calculate the time between closing/opening? i asked this 2 days ago but wasnt sure how to actually do this
yes, save the current time when the app closes and check it when the app opens. calculate how many lobsters you should have earned for the elapsed time
you don't want/need any actual processing to happen in the background while the app is closed.
right but i guess im just confused i minus the time from open to when it was closed? is that withDateTime?
of course
will that also calculate when the app is onpause/focus=false for iphone/android?
?
like the app isnt closed it is just minimized
You get your OnPause/OnFocus etc callbacks and you can do whatever you want in them
DateTime doesn't know or care about any of that, it just tells you the time
sorry im just confused i cant find any documentation on it. i use datetime to calculate when the app is closed but is that actually closed or when it get minimized. sorry if that sounds dumb im just confused lol
not for android/ios onpause onfocus
yes it is there
there is not a special version for iOS/Android
Put in some Debug.Logs and test it out and see how it behaves if you're still not sure.
okay so can i just this app paused class for the whole app then and then just give lobsters to the other script?
or do i put the onapppause function in the file im working with
It's #archived-code-advanced I'm not going to spoonfeed in here. You can figure it out
can i make generic class that accept classes delievered from object and Object, like int, float, GameObject, Monobehaviour etc and in this class check equals '==' or 'Equals'. I can do dynamic type but is there any other solution? I tried IEquatable but: There is no implicit reference conversion from 'UnityEngine.GameObject' to 'System.IEquatable<UnityEngine.GameObject>'.
you can use extension methods
but idk what values you would use to compare equivalence
on what basis are you trying to compare
i want co compare equivalence to the same generic type: like T t1, t2; t1 == t2 or t1.Equals(t2)
you can just override == and Equals
(assuming you need equality based on state instead of reference-identity)
but in generic class i cant just do '==', equals can but GameObject dont have IEquatable. here's short example:
public class TestInt : Test<int> { }
public class Test<T> : MonoBehaviour where T : IEquatable<T>
{
public T t1;
public T t2;
private void Awake()
{
if (t1.Equals(t2))
{
}
//or
if (t1 == t2)// error here
{
}
}
}```
with example should be easier because i think i was misunderstanded ๐
what
are you trying
to compare
every component will have a unique reference id so its impossible for monobehaviours to have established equivalence based on their internal data
so what metric are you wanting to determine equality on]
depends on what T is, for int value, for gameobject classic ==, just like you would do == on any type that has '==' without generic class
dont know why UnityEngine.Object dont have IEquatable
is a generic monobehavior really the data structure you're doing for tho?
like whats the purpose
nah, its just example, you can remove MonoBehaviour there
so all you're saying is you want an interface that enforces the == operator
yea, but i want T to be int,float, gameobject,monobehaviour etc so i cant just add operator interface
public class Test<T> : where T : ==operator if something like this existed ๐
public class TestInt : Test<int> { }
public class Test<T>
{
public T t1, t2;
private void TestMethod()
{
dynamic a = t1;
dynamic b = t1;
if (a == b)
{
}
}
}``` i can do this but im thinking if there is better solution
dynamic is not supported in IL2CPP FYI
is GameObject even derive-able?
No
if you're created a template implementation that requires a derived type of gameobject to implment iequitable, that's impossible code
What's the actual goal here anyway @regal olive
and i said lol, to make this code above work, want to check equals or == in two instances of T
We want to make sure this isn't an XY problem
public class TestClass
public IEquitable first, second;
private void TestMethod()
{
if (first == second)
{
//...
}
}
there you go
that compares any two iequitables
or if you want it templated
if you want to be extra strict
second dont work because you cant do Test<GameObject>, will try first in a 'minute'
the problem i'm 1000% sure you're running into is you're trying to supply something that has no meaningful use for equatable
but you won't tell us what you're using this for
so it's pointless to suggest anything further
right
WHY ARE YOU COMPARING GAMEOBJECTS
i need to find element in list
do
you're actually the most infuriating person i've spoken to in this discord lol
so i'll ask again
what metric are you using to determine gameobject equivalence
sorry.. will figure out it by myself, thanks agaanywayn
in your brain, what does it mean for two gameobjects to be equal
if i have gameobject A and gameobject B, how do you as the person writing this code tell whether they're the same or not
I have a button that calls a static function but whenever I switch between scenes and press that button again, it calls that function more than once, equal to the number of times I switched scenes.
Anyone ever have that problem before?
you're adding the static function as a listener to the button on scene load but never removing it
@regal olive i'm happy to help, but you're literally not answering the questions required to supply you with a meaningful answer
are you trying to see if they're the EXACT same object reference?
or that they have similar transforms?
or their rotation is similar
or they have the same composition of components
i answered and i though that was enough, maybe my english is bad idk, and you only are rude and angry for nothing. im really tired... i will just make walkaround
thanks anyways
are you trying to check if the objects are EXACTLY the same, or have equivalent values?
i can suggest an answer if you answer that
i've asked like 10 times now
try GameObject.ReferenceEquals(first, second). that will return true if they're the same object
i want to act like go1 == go2, for gameobject, but its generic and i want in this generic accept GameObject and also int, i want reference check for classes and == for structs
Is this something that only happens with static functions? Because it doesn't do this when it's not static. Also how can I remove the listener?
can you show me the relevant code
Was an issue I was trying to fix before laptop died. I can later ๐ฌ
is your UI set to dontdestroyonload by any chance
No nothing is like that
because AddListener to unity events removes the listener when the gameobject dies in OnDestroy. if you don't destroy, and you load it multiple times, you'll be adding multiple callbacks
yeah i'd need context unfortunately
it could be a misunderstanding of a number of things, rather than the obvious
feel free to @ me when you're on your computer again
can anyone help? it seems like a coroutine just spontaneously broke after making a build of my project
i didnt change anything between before and after building
it worked before, but just broken and gives that error now
Nobody has no idea
is it possible to convert a piano keyboard note to an input for unity?
maybe some midi magic
it's telling you what the error is
there's an asset store package to interface with midi devices
you can override Equals and cast inside of it. don't overthink this
is it better to have a big ui split into multiple scenes or have it load in from resources?
atm the ui is taking up over 1gb in memory for textures
which is not ideal for a mobile phone
no scenes
you can use uncompressed assets for your UI, but you have to be much smarter about how you compose them
its atm just one big ui in one scene
the largest texture is 18mb which definitely needs optimization
still though, what is best practice?
oh wow
no yea
a lot of this is just optimisation
reduce the maximum size of the textures. if it's bigger than the space it takes on screen there's absolutely no point in that. While compression is not recommended for ui, I'd still use it on mobile platform.
yea I just checked like a lot of the ui texture that have been added and most were set to a compression of 2k
I bumped those down to 512
there is no way any of them are gonna need 2k res
not in this situation at least
and that has helped get the usage for texture 2d down a ton
"i didnt change anything before and after building"
and the code had worked fine before i built...
but right after building it... it just broke
Is OnCollsionEnter raycast based? Or does it use a Grid, quad or oct-trees?
Look into how Physx works
the nvidia one?
sigh turns out... there was a lone "w" in my script that definitely wasnt there when i had the script open yesterday...
nvidia physx seems to support many different ones: https://docs.nvidia.com/gameworks/content/gameworkslibrary/physx/guide/Manual/RigidBodyCollision.html
that still doesn't answer what unity uses
and to prove it wasnt, https://pastebin.com/rQAtwnia a pastebin from yesterday, where there is no "w" before StartCoroutine
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
๐
Why isn't that w underlined in red?
visual no-studio code
If you're not getting autocomplete and errors underlined you need to set up your IDE correctly using the instructions in #854851968446365696
Unless that's just how it looks in VS Code ๐
how do you get a null reference exception from a syntax error
It surely does not make sense and is completely unrelated
tfw linux
ok well nvm it still gives an exception, but now i think its slightly different
i honestly have no clue tho
ill just post all the scripts that are involved in the coroutine producing the error
if thats ok
This is not an #archived-code-advanced topic, you should really move to one of the other code channels
oh
does anybody know a way to know when the Rate Us dialog is closed?
not when user has rated the app but just when the dialog closes
Hey so I have problems with a graphql library...
This line: await request.SendWebRequest(); Throws an error, in the IDE it says it is not awaitable and a longer one in editor
Assets\graphQl-client\Scripts\Core\HttpHandler.cs(53,5): error CS1061: 'UnityWebRequestAsyncOperation' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'UnityWebRequestAsyncOperation' could be found (are you missing a using directive or an assembly reference?)
So I opened a sample project, and wrote just two lines into an async method:
UnityWebRequest request = UnityWebRequest.Post("test", UnityWebRequest.kHttpVerbPOST);
await request.SendWebRequest();
Same error in a blank project. I dont see any other users having this problem and cant find anything about the error message
it's telling you what the issue is
it's not awaitable
all code examples on the internet are using await though
why would reust.SendWebRequest() be await able?
even official unity ones
show me one
yeah but i'm not the same person
i know
my link was in response to them, not to you
there won't be any official unity ones showing await request.SendWebRequest() because it's not awaitable, at least in 2020 LTS
you can use a coroutine, or you can use UniTask
which provides the necessary extension methods, and is all around better for async / await than what exists in unity alone
Well im confused...
This is an interview task, the interviewer gave me a unity version and this exact library: https://github.com/gazuntype/graphQL-client-unity to work with
and this library contains the await code, which is failing
okay
well that's not a unity sample code is it
also that's not what it's saying
just look carefully at what you're doing
Thats not what i meant earlier
you can't wait a UnityWebRequest without an async extension method
use the one from UniTask
install unitask
I am specifically told to use this graphql library, which contains the await code
i know
there is no way for me to switch it
you're not understanding
what that library is giving you back
it's okay
i've told you exactly what you need to do.
I am not producing this error myself. It does not even compile right now.
Like I cant just alter the library code
i don't know
it's a buggy library
use an earlier version of it
i wouldn't use it as is
i wouldnt either, but its a job interview
no way around it
already looked for an older version
last time the errournous file was touched was 2 years ago
yeah that issue that was linked uses an extension method to get around the issue you are describing. It's the same extension method that was shared in the unity answers link i posted
yeah i tried that, sadly it solves other problems, not the one i have
The fact that it's a job interview should make no difference; the whole point of interview questions is for the interviewer to find out how you would handle the given problem in real life. So I recommend you forget about the interview part and imagine you were facing this set of requirements as part of your job.
(Any answer that isn't "the library didn't work, so I didn't do anything" probably puts you ahead of 50% of candidates...)
I mean its just one of two parts of the tech interview, so I already got a lot of stuff ready
Ill just write a mail first and see what their response is
i think it'll work out. the people interviewing you are a bunch of amateurs
if you want to fork the library it's easy. copy the directory that was made in Library/PackageCache into Packages
boom, you made a local copy
@olive cipher what v of unity are you in?
2019.4.16f
library was a unity package + github, so no problem, solved it with an own get request + parser for graphql now, just a quick hack but it does what it should without causing further trouble
I wouldnt say so, unity just bought the company I have my interview at ๐คฃ
This is the result btw, time constraint was around 16h
Done for mobile
Weta Digital?
nah
looks good
we shall see
DM me what the result is ๐
Is there any functional or performance difference between:
public delegate void StatChangedDelegate(Stat stat, int currentValue, int amount);
public event StatChangedDelegate onStatChanged;
and instead doing:
public event Action<Stat, int, int> onStatChanged;
NM, did some searching and turns out the compiler treats both as the same
i would recommend using unirx to do stuff like this
since C# events are pretty clunky
im using graphics.DrawMesh in editor onPreCull, about 10 calls per frame, the problem is that the performance of the sceneview where im drawing degrades over time significantly, the degradation is faster with DrawMeshInstanced, profiler shows like 20k calls in BatchedRenderer.Flush, so my assumption is that the draw calls are accumulated, the issue dissapears upon moving any object in scene or alt tabbing, but if i just use the camera for navigation the issue persists
declaring your own delegate types is a throwback to the time before the framework added Actionand Func
that is wrong
yeah?
yeah
how so?
Action<SomeTypeHoldingAllThoseFloatsWithNamesEven>
that is an argument unrelated to delegates
same for methods and the container struct/object is losing due to many issues
Would you consider an anecdotal argument, then? ๐ I have 20 years of C# experience and haven't written any new delegate types since Actionand Func were added (also EventHandler<T>)
arguments from authority dont work really
You do you
i just said its objectively wrong, typed delegates are used widely for exactly the purpose they were designed for, and avoiding them means using wrong instruments for the wrong tasks
I also prefer delegates since mousing over the method gives you names for the args, as opposed to just arg arg arg arg arg ๐
what's your objective?
Absolutely not true. Action and func are the only ones used except in extreme edge cases
I fully agree with rogue code on this one
I'm definitely not a professional C# developer but I prefer declaring my own delegate types for clarity.
I don't like using Tuples either
Epic online service interfaces has so many delegate types
Shockingly they're all used
Hello, I am currently trying to get source generators running in Unity 2021.2. I have followed this documentation here: https://docs.unity3d.com/2021.2/Documentation/Manual/roslyn-analyzers.html
Normal analyzers are getting picked up but it looks like not the source generators. Someone already got it working?
this normal?
it's a matter of preference really. I won't boast about my experience in C# but I've seen vastly experienced developers using either of them depending on their preferences.
Action<float,float,float> could also use another line of documentation where the comment says what exactly the parameters are.
I'm a Action, Func guy aswell but i do use delegates sometimes in some other project (at work or some pr) to maintain source code consistency
Using a custom delegate too, when the commonly used Action and Func are too "generic" ie. the parameters could be unclear.
yeah you were right, I wasn't removing the listener. thanks!
A bit late, but that made me think about WPF (a C# UI framework) commands.
Basically in WPF we have a ICommand interface that declares two methods, CanExecute and Execute, that does roughly what you want. It's an interface after all, so the job is yours to implement the concrete classes.
For example, a RelayCommand<T> class that implements ICommand, where you supply two delegates (for Execute and CanExecute) that will be run appropriately.
The type argument is here, so an instance of that type is passed to Execute as a parameter.
Ayy blast from the past. Glad you figured it out
I don't really see an issue here, your commands are declared on the cards directly, and you could expose events that get raised when the state changes. CanExecute could raise the event, and some manager class subscribing to it, catches it and updates state
Hey, i think this code is for the advanced section, because it includes physics, but can someone check it and explain to me why sometimes the "obstacleCheckRadius" fails to apply. Meaning two "Trees" spawn really close to each other or sometimes a tree spawns on my player. - https://pastebin.com/DtFsdpaX
I will appreciate any help or advice, been struggling with this for a couple hours now
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
still looking for answer btw, i'm pretty much stuck on this
@fierce holly have you tried attaching a debugger and setting breakpoints around the code youโre concerned with?
how can i do this? i did a little debugging and tried a lot of different values, but i can't understand what's happening
I bet the issue might be on line 50 of your pastebin. How to attach a debugger? Hereโs unityโs documentation: https://docs.unity3d.com/Manual/ManagedCodeDebugging.html
ะkay let me give some more information. I did a lot of value testing and so far confirmed that the radius works, but i feel like it's checking only the last Obstacle, and not all previously spawned obstacles.
e.g. These two trees spawned very close to each other
and the debug log, showing in which attempt it spawned and which collisions it detected
When i try to spawn 100 trees with a radius of 15, only 2 or 3 trees spawn, which seems correct given how many space there is on the scene
when i try to spawn 1000 trees with 1 or 2 radius, they spawn like this
positions look a bit weird of course, but i think this is another issue with how my map and the weird positions i'm generating to stay on the map position = new Vector3(Random.Range(-18f, 6f), 0, Random.Range(-18f, 6f));
and here is an attempt where it spawned on top of my player, i had also moved the debug.log before the if statement to see all collisions
sorry for all the spam, but there is something weird going on with my code that i really want to understand ๐
That looks like a neat project!
Maybe try to assign the trees prefab to a layer and use a layer mask in the โPhysics.OverlapSphereโ method call
Thank you a lot! Sounds like a great suggestion that I will gladly try out!
As for the game, i have just a few more systems I want to implement and then I will focus on art and polish.
I will share it somewhere here if I manage to finish it in time for Christmas ๐
let's start from the beginning. you have this process that looks like
try to add something to a space
is it valid? great. change the space, repeat.
is it not? bad. don't change the space, repeat.
so you have to waste a lot of time either way - the space changes, or you did nothing
you're also conflating these two objectives - you don't want the trees to be too tight together for gameplay purposes, but also you want the trees to look like they've been placed organically
a good approach is to make things placed gameplay wise right from the get-go, all of the trees all at once
and then somehow modify that to make it look organic
@fierce holly my suggestion is to fill a grid with trees, where the distance between each tree is valid, and then remove them until you have your desired count
remove them at random. then, maybe move them a tiny bit. it'll look organic
you can also approach it as, place it organically, then modify it to be gameplay correct
in real life, trees grow from seeds falling from pre-existing trees, so you should take an approach like that
randomly filling a field doesn't really work
Looks like an interesting approach, thank you for suggesting! Do you thing this will work in run-time. My goal is not from the trees to be generated at start, but in the middle of game, while you are playing
Itโs like an extra challenge that will make it harder to dodge for some time
yes, if you take the approach of filling a grid then slightly tweaking the position
you will have only visited each tree a fixed number of times, and that's it
it's up to you
it's all sort of the same
I was considering as an alternative splitting the map into quadrants, then spawning one tree in each quadrant. Is this approach similar to what you are suggesting, havenโt worked with grids before
sure
I see, this is very helpful. Thank you for taking the time to look into it!
i don't think so
The method doctorpangloss descirbed is basically a "poisson distribution".
Just doing a perterubed grid + randomly picking points within grid (with some "padding") will give you basically the same thing.
So yeah, that's a good idea imo ๐
Further reading https://www.jasondavies.com/poisson-disc/
Perfect, thank you very much!
Hey guys, I'm trying to achieve to have a cannon do target leading and shoot at calculated intercept, my results turns out to be insanely jittery and not correct. Is someone experienced with this?
I can send a short MP4 to show it and the code ofcourse
I think it maybe a wrong calculation of time to impact or my turret is not turning correctly, but I can't seem to really find the problem
Is it alright to use multiple interfaces per script?
Yes
Awesome, thx!
I think I've solved it, was squaring something that should not have been squared
Greetings everyone. I am generating AudioClips at runtime and I'm experiencing clicks and glitches in certain waveforms.
Here is my code that generates the Audio:
void GenerateAudio()
{
for (int j = 0; j < notes.Length; j++)
{
float[] samples = new float[44000];
for (int i = 0; i < samples.Length; i++)
samples[i] = (Mathf.Repeat(i * notes[j].Frequency / 44000, 1) > 0.5f) ? 1f : -1f;
AudioClip ac = AudioClip.Create("Clip", samples.Length, 1, 44000, false);
ac.SetData(samples, 0);
rectangleClips.Add(ac);
}
for (int j = 0; j < notes.Length; j++)
{
float[] samples = new float[44000];
for (int i = 0; i < samples.Length; i++)
samples[i] = Mathf.Sin(Mathf.PI * 2 * i * notes[j].Frequency / 44000);
AudioClip ac = AudioClip.Create("Clip", samples.Length, 1, 44000, false);
ac.SetData(samples, 0);
sineClips.Add(ac);
}
for (int j = 0; j < notes.Length; j++)
{
float[] samples = new float[44000];
for (int i = 0; i < samples.Length; i++)
samples[i] = Mathf.PingPong(i * 2f * notes[j].Frequency / 44000, 1) * 2f - 1f;
AudioClip ac = AudioClip.Create("Clip", samples.Length, 1, 44000, false);
ac.SetData(samples, 0);
triangleClips.Add(ac);
}
for (int j = 0; j < notes.Length; j++)
{
float[] samples = new float[44000];
for (int i = 0; i < samples.Length; i++)
samples[i] = Mathf.Repeat(i * notes[j].Frequency / 44000, 1) * 2f - 1f;
AudioClip ac = AudioClip.Create("Clip", samples.Length, 1, 44000, false);
ac.SetData(samples, 0);
sawtoothClips.Add(ac);
}
Debug.Log("Audio Generated");
}
Master is the AudioSource Component of the Gameobject. In Sine and Triangle it clicks at the end and in Sawtooth and Rectangle the sound glitches sometimes.
Does anyone here got experience with generating AudioClips at runtime?
use cs or csharp for syntax highlighting and it should be on the same line as the `s. No suggestions for your actual issue though...
does it still clip if you use https://docs.unity3d.com/ScriptReference/AudioClip.SetData.html
sorry, what I meant to say was does it play without clipping if you immediately play the audioclip instead of adding it to the list (s)
It also clips, I added the lists to see if it helps to pre-generate the clips before playing them
but it didn't
Here is an example of what it sounds like. Interestingly certain pitches are not as affected as others, for example G3 in all Waveforms only clicks really quietly while looping, but others are really loud.
it might not be the audio clip but the playback
unity has issues playing audio without dropping audio sample if you just call to play a sound
you can use this if you don't already do
https://docs.unity3d.com/ScriptReference/AudioSource.PlayScheduled.html
SideNote: The Audioclip has to play immediatly when a button is pressed and has to end immediatly when a button is released. PlayScheduled would be impossible since the system cannot know when the player will press a button.
I mean, this is a silly question, but are they set to loop? There may be a click/glitch at end of clip otherwise
Also, the 44000 in the sample creation can be a float, and that may take care of some of it. I did something similar a while back and am trying to find the code.
(this i mean)
samples[i] = Mathf.Sin(Mathf.PI * 2 * i * notes[j].Frequency / 44000);
You can use the playSchedules like Malzbier said with the current DSP time i.e.
audioSources[i].PlayScheduled(AudioSettings.dspTime);
I fixed the in-loop clicking by adjusting the sample length by the frequency
float[] samples = new float[(int) (44000 / notes[j].Frequency)];
interesting, glad it's working!
But!
How do I stop the wave at 0
Is there a way to get the current stream and detect when it's 0 and then stop it?
You probably need to calculate when the waves are 0, and choose some X count of waves to put in the sample list.
Since you know the frequency, you should know the wavelength, which means you can tell it to store X waves as samples by length?
the length is determined by how long the player holds the button
Sorry, I mean if you're playing a square wave at 440hz, that means you have 1 square wave every 1/440 of a second, and so you can make the length of samples match when the wave should hit 0, if that makes sense
But that doesn't stop the player from releasing the button when the sample isn't finished, does it?
lmao of course, hmm, can you just fade it out really quickly as a hack? ๐
I mean, that's how analog synths work I think, since the cap has to drain when you release, I dunno how things like DAWs handle it
It's dumb, but apparently thats what most of google says to do as well lol
I wonder if I can't calculate the exact 0 point from there
Makes sense yeah
