#archived-code-advanced

1 messages ยท Page 154 of 1

median cosmos
#

it still doesn't work, they can still do this

misty glade
#

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()

remote oar
#

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

median cosmos
#

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

misty glade
#

Yup was talking to mike ๐Ÿ™‚

torpid sky
#

@misty glade

Vector3 direction = (previousPositions[i] - currentPosition);

rather than

Vector3 direction = (currentPosition - previousPositions[i]);

fixed it :omegalul:

misty glade
#

ha, weird

torpid sky
#

I thought that would be literally the same ray

misty glade
#

it was drawing the debugrays backwards and keeping the wrong magnitude as a result

#

it seems like it should still have worked?

#

heh

torpid sky
#

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

misty glade
#

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

torpid sky
#

the collider is a capsule that is roughly the size of his body

#

maybe it's too small

torpid sky
#

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%?

compact ingot
torpid sky
#

?

#

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

odd mesa
#

hey guys what up

#

am building a blockchain game having some mare difficulties might need hands

torpid sky
#

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

torpid sky
#

yes I found that function too

#

but I don't understand what it's really doing

#

the docs aren't very helpful

compact ingot
#

it applies the animation clip at t to the go

torpid sky
#

what does that mean

#

why do I need a GameObject for this?

vestal idol
#

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

narrow lodge
#

Sorry was running errands, but yeah.

vestal idol
#

it's not null because i tried if (arr[some number] == null) Debug.Log("hi")

#

and nothing was printed

compact ingot
vestal idol
#

ah

compact ingot
#

source of "GameObject' has been destroyed but you are still trying to access it." errors

reef void
#

Anyone know how to make a seamless portal

plush hare
#

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 >=

compact ingot
reef void
#

im using a different player controller so maybe that's why

#

in my heirarchy i have a player and a camera that are seperate

compact ingot
#

sorry, i'm not familiar with brackey's tutorials

rugged pollen
#

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.

compact ingot
rugged pollen
#

yeah, currently using Node Canvas + tasks written by yours truly

compact ingot
#

i'd basically recommend exactly that

rugged pollen
#

so FSM for waypoint => attack states (plus whatever)

compact ingot
#

moba creeps aren't really smart so you cant go wrong really, no matter what you do i guess

rugged pollen
#

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

compact ingot
#

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)

rugged pollen
#

both good ideas -- have some sense of aggro thing that I'm still sorting out -- it's single player thankfully ๐Ÿ™‚

vestal idol
#

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?

vestal idol
#

nvm

fervent sage
#

Googling keeps getting me standard collision detection, not my specific problem of a lead, the only other solution I found being an estimation

snow grotto
#

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

real blaze
#

I'm sure you already know, but just in case : you can find the direction out with a simple vector.dot product

snow grotto
#

Thanks, I'll try that, I was planning on doing it that way ๐Ÿ‘

eternal parrot
#

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?

devout hare
#

Because the first one is just nonsense

drifting galleon
devout hare
drifting galleon
#

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

topaz imp
#

it's fun just randomly looking at code which i have no idea about

hollow wing
#

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

gray pulsar
hollow wing
#

I'm not

gentle topaz
#

it doesn't run "in the physics loop," it runs after Update

long ivy
gentle topaz
#

the physics loop just runs before Update

hollow wing
#

@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

gray pulsar
#

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.

gentle topaz
#

then everything you said makes perfect sense based on this execution order

wooden cedar
#

Physics doesn't run at the same time as Update, different time signatures and frequency

gentle topaz
#

or wait, you said the TriggerStay happens after the coroutine?

hollow wing
#

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
gray pulsar
#

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.

wooden cedar
#

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

hollow wing
#

(moved up to the rest)

gray pulsar
wooden cedar
gentle topaz
hollow wing
#

@wooden cedar check the example please - i think it should answer it?

hushed fable
#

I imagine you would get both twice if either of them run twice?

wooden cedar
gray pulsar
#

another dumb question. Any chance your logs are set to collapse?

hollow wing
#

damn sorry danon

#

corrected it now - first FixedUpdate

long ivy
#

this still looks correct to me. I'm guessing you're starting the coroutine inside OnTriggerX or OnCollisionX

hollow wing
#

@gentle topaz I don't follow so far

#

currently the Coroutine is between FixedUpdate and OnTriggerStay

#

that is the physics loop

gentle topaz
#

yup

#

wait... am I insane?

#

I think so

hollow wing
#

yeah I think you're incorrect

gentle topaz
#

where are you actually starting the coroutine?

#

what is the full testing code here

wooden cedar
#

That's what I was saying

hollow wing
#

there is no testing code. I entountered that in my project

wooden cedar
hollow wing
#

that's a very vague statement. I can't get much information from that

wooden cedar
#

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

hollow wing
#

added one

#

as in my code the Debug is at the beginning of the coroutine this is still the valid simplification

wooden cedar
#

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.

hollow wing
#

I explained you how the coroutine is started

wooden cedar
#

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

gray pulsar
#

he said it runs from Update

hollow wing
#

I explained in the beginning that it was started at a random point in time during the program, and said also inside Update

wooden cedar
#

This whole convo could have been avoided with the code being complete.

hollow wing
#

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

exotic glacier
#

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?

wooden cedar
hollow wing
#

@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?

gentle topaz
#

I think you made a mistake, because I compile this

#

and get this

hollow wing
#

ok thank you for testing it

#

can you send the code quickly

#

dm or sth to avoid spam

gentle topaz
#
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;
        }
    }
edgy drift
#

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

gentle topaz
wooden cedar
edgy drift
#

mm ok, i forget there was a example project tbh

wooden cedar
hollow wing
#

@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)

gentle topaz
#

I mean, I think that it is going to always end up exactly as the documentation says

wooden cedar
#

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?

gentle topaz
#

when you isolate the problem

hollow wing
#

I mean I'm stuck here and asking for some help

gentle topaz
#

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

wooden cedar
hollow wing
#

I mean I'm uncomfortable with sending my full code if that's not clear

gentle topaz
#

well, yeah that seems to be pretty obvious... but as for the reasoning? I cannot imagine why

wooden cedar
#

@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.

hollow wing
#

It's nice they did that. I didn't ask them

hollow wing
gentle topaz
#

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

wooden cedar
#

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...

hollow wing
#

i wanted to dm those to you. The offer still stands, but I can't dm you because you disabled it

wooden cedar
#

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.

gentle topaz
#

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

near sage
#

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());

hollow wing
#

@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

near sage
#

Nvermind I solved it

wooden cedar
hollow wing
exotic glacier
#

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.

frozen stump
#

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

vestal idol
#

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

gray pulsar
vestal idol
#

how would q n or w be null? they are int

gray pulsar
vestal idol
#

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

gray pulsar
#

if those are all ints, the only way that line gives you a nullrefexception is if array is null. ๐Ÿคทโ€โ™‚๏ธ

vestal idol
#

yea thats strange af lmfao

#

but then it should give me outofbounds instead

#

if the array is null?

gray pulsar
#

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
vestal idol
#

i see

#

so what if you have someobject[] array = {null, something, something}

#

and then did array[0]

#

would that yield null ref

gray pulsar
#

that would return a value of null

#

no exception

vestal idol
#

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?

gray pulsar
#

you could like... try debugging it? that's not too hard to test

vestal idol
#

yea but how would i test

#

if i cant even access

#

array[q,w]

#

o shit

#

hahahaha ur right

gray pulsar
#

dude, you're posting in #archived-code-advanced. these are the kinds of things that a beginning c# tutorial would teach

vestal idol
#

o mb

#

so should i keep posting here?

#

and we type in beginner code?

#

i solved the issue thanks @gray pulsar

gray pulsar
vestal idol
#

no its g

nocturne osprey
#

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();
drifting galleon
#

what seems wrong?

nocturne osprey
#

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 )

reef void
#

anyone know how i could make some stars that move, grow and shrink to put inside of an inverted sphere skybox?

quartz stratus
dense aspen
wooden cedar
#

I'd probably make a shader for it tbh

cloud crag
#

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?

regal lava
#

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

cloud crag
#

why should I not use Animator and use e.g. enums or my own statemachine

regal lava
#

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.

regal olive
compact ingot
regal olive
#
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

real blaze
#

Which brings up a good question ๐Ÿค”

Is particle system more efficient than a bunch of sprites?

topaz imp
#

its so fun looking through this channel and understanding that i dont understand anything

queen plover
#

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.

regal olive
#

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?

verbal peak
regal olive
verbal peak
#

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

regal olive
#

RIGHT?!?

#

I bet you there is someone out there RIGHT NOW that is doing just that.

verbal peak
#

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

regal olive
#

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. ๐Ÿคž

verbal peak
#

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

regal olive
#

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

regal olive
# verbal peak Itโ€™s why Iโ€™m pretty skeptical about anyone actually writing something like this ...

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.

small badge
#

@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.

regal olive
# small badge <@456226577798135808> From my experiences working for many many years on large e...

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.

warm spade
#

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?

wooden cedar
# regal olive I appreciate the perspective! I humbly, respectfully disagree. In the "Unit Test...

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.

regal olive
#

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

wooden cedar
#

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

regal olive
#

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!

small badge
#

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.

regal olive
#

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 ๐Ÿ˜

livid kraken
#

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.

small badge
# regal olive I disagree fundamentally (but respectfullyโ€” thank you all for your thoughts!). I...

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.)

regal olive
#

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.

warm spade
#

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

wooden cedar
#

Thatโ€™s how I did my diablo 2 hacking back in the day, just read the memory values

wispy lion
# warm spade There's a ghost hunting unity game where you gather all kinds of evidence in ord...

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...

โ–ถ Play video
wooden cedar
# regal olive It is enlightening to see these thoughts. One takeaway I have is that the value ...

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.

warm spade
# wooden cedar I probably wouldnโ€™t do this. You can access windows frame information / memory ...

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

wooden cedar
#

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

warm spade
#

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'

wooden cedar
#

That would be a question to ask the game creators in that case

hushed fable
#

Game of that size definitely has some sort of modding community, so I would seek those out instead

warm spade
#

The game is pretty big but unforunately there really are no mods for it, I don't know the reason

lime violet
# regal olive I wonder if there is a more easy way to do it

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)

warm spade
wooden cedar
regal olive
#

Will check that spider video

warm spade
lime violet
regal olive
#

Thanks, will compare it with what I was doing, maybe his approach is a better one

edgy drift
#

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

regal olive
# wooden cedar With Unity, every team and company has different patterns and processes - making...

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.

wooden cedar
# regal olive Hmm this scenario is missing a crucial fact. Is there already coverage preexisti...

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

regal olive
wooden cedar
regal olive
wooden cedar
#

I also, to be clear, hold that to myself for not explaining well

regal olive
#

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

wooden cedar
#

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

regal olive
#

Both ways have pros and cons. Big trade offs in general

lofty inlet
#

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?

wooden cedar
#

No, you would need to write something that stores a base64 to the clipboard

#

Or use this, Google is your best friend :)

lofty inlet
#

actually didn't think something like this would be on google lol

wooden cedar
#

I'm not sure if base64 would even still do it these days, so I'd definitely use existing APIs

lofty inlet
#

so I'd have to use an external source to get this to work and not default unity/c# code?

regal olive
wooden cedar
#

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.

regal olive
#

If something is inviting you to download and install a library, I say that is overkill for your use case

lofty inlet
#

yeah

#

alright sounds good I'll try it

#

thanks

wooden cedar
#
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 :)

edgy drift
frigid elbow
edgy drift
#

sure 1 sec

edgy drift
#
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?

frigid elbow
#

Yes the Player Controller please.

edgy drift
#

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);
    }
}
frigid elbow
edgy drift
#

player controller

#

player manager

frigid elbow
#

btw, what happens if you make the PhotonView PV to public PhotonView PV and then set the PhotonView in the inspector?

edgy drift
#

made no diffrence

frigid elbow
#

On Photon View component try to change the Sync choice.
It's on Unreliable On Change

edgy drift
#

mm ok

frigid elbow
#

What's the options?

#

It's 3 options right?

edgy drift
#

yea

frigid elbow
#

Does manual exists?

edgy drift
#

i think i tried that already but i will again

frigid elbow
#

Wait..

#

Is it the Auto Find all that has an manual?

edgy drift
frigid elbow
#

Take manual

#

Now the Observed comps should be on?

edgy drift
#

yea

frigid elbow
#

Oh

#

Okay

#

Test that?

#

Otherwise i have one more solution in mind

edgy drift
#

it does the same

frigid elbow
#

Okay

edgy drift
#

i tried that already

frigid elbow
#

What happens if you delete the Photon Transform View?

#

And use the old one?

#

There's two of them

#

One with more options..

edgy drift
#

oh ill see

#

i enabled the rot and pos

frigid elbow
#

Btw, are you following an tutorial/course?

#

Yes try that

edgy drift
#

i was following a tutorial

#

but i stopped becasue of this bug

frigid elbow
#

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

edgy drift
#

yea

frigid elbow
#

Where is the PlayerManager script located?

#

(In the scene Game)

#

RoomManager?

edgy drift
#

player manager is only on the player manager prefab

edgy drift
frigid elbow
#

But the player spawns in via the PlayerManager script?

#

But what triggers the PlayerManager?

edgy drift
#
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

frigid elbow
#

Okay..
What is the diffrence between PlayerControll & PlayerController?

edgy drift
#

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

frigid elbow
#

Can you show me a picture of PlayerController prefab?

edgy drift
frigid elbow
#

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.

edgy drift
#

its sending a video file itll just be a sec

#

theres this whilst its running

frigid elbow
#

The Photon Transform View is still like in the prefab? (When not playing)

edgy drift
#

im not sure what you mean..?

#

do you want me to send a pic of the prefab when its not running

frigid elbow
#

No a pic just like you did

#

but with the photon transform view

edgy drift
#

thats when not running

frigid elbow
#

When its* running

#

Just to make sure nothing has turned it off

edgy drift
#

thats when its running so i think nothing has turned it off

#

oh theres the video

frigid elbow
#

Well, that should sync?!

edgy drift
#

thats what i thought....

frigid elbow
#

If you move you change the PlayerController gameobject transform right?

#

So you are syncing the right object

edgy drift
#

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

frigid elbow
#

This is not making sense for me either..

edgy drift
#

i could send you the entire project file?

#

its 180mb so ill compress it and upload it to something like mega

mint mural
#

use github

#

or gitlab

#

but stop using zip ;-;

edgy drift
#

mm

#

why..?

mint mural
#

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

edgy drift
#

fair enough

frigid elbow
#

Github or Gitlab is a good Version control system.

mint mural
#

yes

#

don't use unity collab

frigid elbow
frigid elbow
mint mural
#

yup github is a good one

edgy drift
edgy drift
mint mural
#

basically tells to git what needs to be uploaded, and what shouldn't

edgy drift
#

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

mint mural
#

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! ๐Ÿ˜„

edgy drift
#

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

mint mural
#

yup that's the right thing to do:D

edgy drift
#

is github usually this slow...

mint mural
#

no ๐Ÿ˜‚
you just have a bad connection :/

edgy drift
#

just started that

#

its the discord client

#

litterly just started it

edgy drift
edgy drift
sour lynx
#

hi, this is just a question, how much servers allow free photon license?

merry robin
shadow seal
#

Photon is sort of a blanket term, there are many Photon products. Pretty sure pricing is on their website

versed nest
#

(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

merry robin
#

how big are said images? (resolution? format? etc)

versed nest
# merry robin 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)

merry robin
#

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.

versed nest
#

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

merry robin
#

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

versed nest
# merry robin you can also always convert image data in a background thread to GPU-ready data ...

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?

merry robin
#

if using FreeImage I'd just do it myself with C# threads.

#

anything that doesn't touch the main worker

versed nest
#

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!

real slate
#

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?

regal olive
#

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

#

sr

regal olive
#

oh

pastel horizon
#

I've a problem with sorting layers. How can I solve this: platforms < player < water but also platforms> water
< means higher sorting layer

drifting galleon
somber grotto
#

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

median cosmos
#

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

regal olive
#

anyone here with experience in quaternions?

median cosmos
regal olive
median cosmos
#

instantly

#

or on time

regal olive
#

instantly

median cosmos
#

ah

#

I think you don't even need to use Quaternions for that

#

you could just use transform.eulerAngles I think

regal olive
#

yea thats whats im reading now but i tried it and guess what

median cosmos
#

which works in Vector3

regal olive
#

i get -180 on x

median cosmos
#

or Vector2

#

what did you write?

regal olive
#

GameObject.Find("Left").transform.eulerAngles = new Vector3(0, 180, 180);

median cosmos
#

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

regal olive
#

is there a local version?

median cosmos
#

yes

#

just with local

#

localEulerAngles

regal olive
#

still -180 on x

median cosmos
#

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

regal olive
#

the object is not a child btw

median cosmos
#

k

regal olive
#

when i rotate it in the editor it works, via script it doesnt

median cosmos
#

hmm yeah you're write

#

I'm probably missing some basic knowledge and you too๐Ÿ˜‚

regal olive
#

lmao

#

unity is missing basic logic

sly grove
#

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

regal olive
#

docs literally say use euler not quaternion lol

sly grove
#

what docs

regal olive
#

anyway with quaternion z works, y fcks up

#

unity docs

sly grove
#

Which part?

somber grotto
median cosmos
#

yeah

merry robin
#

Full stop. Do not directly manipulate Quaternions. Use the helper functions ie: AngleAxis, FromToRotation, Quaternion.Euler

median cosmos
#

I tried that too

sly grove
#

If you want to rotate on two axes at once it's usually best to create a parent pivot object.

median cosmos
sly grove
#

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

somber grotto
median cosmos
#

well

merry robin
median cosmos
#

but what's the reason for it

sly grove
devout hare
#

The issue is that Euler angles aren't unique. Rotation of (0, 180, 180) is exactly equivalent to (-180, 0, 0)

somber grotto
#

huh last time i checked they were orange

#

ah yeah mods are also orange

#

makes sense

regal olive
#

Quaternion.Euler gives -180 on x

median cosmos
#

and 720 will be converted to 0 right so you can't rotate by 720 degrees on time?

somber grotto
sly grove
#

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

merry robin
devout hare
median cosmos
#

I mean rotating in time

#

of course it's the same endrotation

#

but it also wouldn't rotate at all right?

devout hare
#

No problem there

#

if you add e.g. 1 degree every frame it'll rotate just fine up to 720 degrees

median cosmos
devout hare
#

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

thick birch
#

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

pastel horizon
#

I've a problem with sorting layers. How can I solve this: platforms < player < water but also platforms> water
< means higher sorting layer

pastel horizon
sly grove
#

which doesn't make sense

pastel horizon
#

I make a 2.5D game

sly grove
#

also this isn't a code question

pastel horizon
#

The player should be in front of the platforms

#

because of 2.5 D

sly grove
#

maybe draw a picture of what you want

pastel horizon
#

and the platforms should be higher than the water

sly grove
#

In the appropriate channel

pastel horizon
#

ok

exotic glacier
#

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

sly grove
#

you don't want/need any actual processing to happen in the background while the app is closed.

exotic glacier
#

right but i guess im just confused i minus the time from open to when it was closed? is that withDateTime?

sly grove
#

of course

exotic glacier
#

will that also calculate when the app is onpause/focus=false for iphone/android?

sly grove
#

?

exotic glacier
#

like the app isnt closed it is just minimized

sly grove
#

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

exotic glacier
#

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

sly grove
#

Have you checked the Unity manual/scripting API?

#

the documentation is all there

exotic glacier
#

not for android/ios onpause onfocus

sly grove
#

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.

exotic glacier
#

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

sly grove
exotic glacier
#

sorry i thought it meant too advanced for me XD

#

i got it thanks for your help!!!

regal olive
#

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>'.

humble loom
#

you can use extension methods

#

but idk what values you would use to compare equivalence

#

on what basis are you trying to compare

regal olive
#

i want co compare equivalence to the same generic type: like T t1, t2; t1 == t2 or t1.Equals(t2)

compact ingot
#

you can just override == and Equals

#

(assuming you need equality based on state instead of reference-identity)

regal olive
#

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 ๐Ÿ˜›

humble loom
#

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]

regal olive
#

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

humble loom
#

is a generic monobehavior really the data structure you're doing for tho?

#

like whats the purpose

regal olive
#

nah, its just example, you can remove MonoBehaviour there

humble loom
#

so all you're saying is you want an interface that enforces the == operator

regal olive
#

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
sly grove
#

dynamic is not supported in IL2CPP FYI

regal olive
#

oh..

#

didnt know

#

hmm i can do abstract Equals method and override

humble loom
#

is GameObject even derive-able?

sly grove
#

No

humble loom
#

if you're created a template implementation that requires a derived type of gameobject to implment iequitable, that's impossible code

sly grove
#

What's the actual goal here anyway @regal olive

humble loom
#

ive asked him 3 times

#

i still dont have an answer lol

regal olive
#

and i said lol, to make this code above work, want to check equals or == in two instances of T

humble loom
#

we know you're trying to get your code to work

#

what is the purpose of your code

sly grove
#

We want to make sure this isn't an XY problem

humble loom
#
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

regal olive
#

second dont work because you cant do Test<GameObject>, will try first in a 'minute'

humble loom
#

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

regal olive
#

i need to find element in list

humble loom
#

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

regal olive
#

sorry.. will figure out it by myself, thanks agaanywayn

humble loom
#

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

surreal nebula
#

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?

humble loom
#

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

regal olive
#

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

humble loom
#

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

regal olive
#

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

surreal nebula
humble loom
#

can you show me the relevant code

surreal nebula
#

Was an issue I was trying to fix before laptop died. I can later ๐Ÿ˜ฌ

humble loom
#

is your UI set to dontdestroyonload by any chance

surreal nebula
#

No nothing is like that

humble loom
#

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

ebon depot
#

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

zenith ginkgo
#

Nobody has no idea

frozen flare
#

is it possible to convert a piano keyboard note to an input for unity?

#

maybe some midi magic

undone coral
undone coral
undone coral
heady bane
#

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

untold moth
#

1GB for ui?? Maybe optimize your assets..?

#

Is it a different ui in every scene?

undone coral
heady bane
#

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

untold moth
#

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.

heady bane
#

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

ebon depot
#

and the code had worked fine before i built...

#

but right after building it... it just broke

bold flare
#

Is OnCollsionEnter raycast based? Or does it use a Grid, quad or oct-trees?

austere jewel
bold flare
#

the nvidia one?

ebon depot
bold flare
#

that still doesn't answer what unity uses

ebon depot
#

๐Ÿ–•

austere jewel
#

Why isn't that w underlined in red?

ebon depot
austere jewel
#

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 ๐Ÿ‘€

modest lintel
#

how do you get a null reference exception from a syntax error

austere jewel
#

It surely does not make sense and is completely unrelated

ebon depot
#

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

austere jewel
ebon depot
#

oh

stuck onyx
#

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

olive cipher
#

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

undone coral
#

it's not awaitable

olive cipher
#

all code examples on the internet are using await though

undone coral
#

why would reust.SendWebRequest() be await able?

olive cipher
#

even official unity ones

undone coral
#

show me one

undone coral
#

it's the same question

#

the answer also says what the issue is

#

it's not awaitable

thin mesa
#

yeah but i'm not the same person

undone coral
#

i know

thin mesa
#

my link was in response to them, not to you

undone coral
#

the person responded, "it's not awaitable"

#

oh my bad lol

undone coral
#

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

olive cipher
#

and this library contains the await code, which is failing

undone coral
#

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

olive cipher
#

Thats not what i meant earlier

undone coral
#

you can't wait a UnityWebRequest without an async extension method

#

use the one from UniTask

#

install unitask

olive cipher
#

I am specifically told to use this graphql library, which contains the await code

undone coral
#

i know

olive cipher
#

there is no way for me to switch it

undone coral
#

you're not understanding

#

what that library is giving you back

#

it's okay

#

i've told you exactly what you need to do.

olive cipher
#

Like I cant just alter the library code

undone coral
#

i don't know

#

it's a buggy library

#

use an earlier version of it

#

i wouldn't use it as is

olive cipher
#

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

thin mesa
#

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

olive cipher
#

yeah i tried that, sadly it solves other problems, not the one i have

small badge
# olive cipher i wouldnt either, but its a job interview

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...)

olive cipher
#

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

undone coral
#

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

quartz stratus
#

@olive cipher what v of unity are you in?

olive cipher
#

2019.4.16f

olive cipher
olive cipher
#

Done for mobile

formal lichen
#

Weta Digital?

olive cipher
undone coral
#

looks good

undone coral
#

DM me what the result is ๐Ÿ™‚

flint wind
#

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

undone coral
#

since C# events are pretty clunky

plucky laurel
#

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

fallow lantern
fallow lantern
#

yeah?

plucky laurel
#

yeah

fallow lantern
#

how so?

plucky laurel
#

Action<float,float,float,float,float>

#

explain what third param does

fallow lantern
#

Action<SomeTypeHoldingAllThoseFloatsWithNamesEven>

plucky laurel
#

that is an argument unrelated to delegates

#

same for methods and the container struct/object is losing due to many issues

fallow lantern
#

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>)

plucky laurel
#

arguments from authority dont work really

fallow lantern
#

You do you

plucky laurel
#

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

flint wind
#

I also prefer delegates since mousing over the method gives you names for the args, as opposed to just arg arg arg arg arg ๐Ÿ™‚

drifting galleon
#

I fully agree with rogue code on this one

sly grove
#

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

slender oracle
#

Epic online service interfaces has so many delegate types

austere jewel
#

Shockingly they're all used

fading radish
cedar ledge
#

this normal?

tough tulip
# drifting galleon Absolutely not true. Action and func are the only ones used except in extreme ed...

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

fresh salmon
#

Using a custom delegate too, when the commonly used Action and Func are too "generic" ie. the parameters could be unclear.

surreal nebula
fresh salmon
#

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.

humble loom
fresh salmon
#

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

fierce holly
#

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

fierce holly
#

still looking for answer btw, i'm pretty much stuck on this

regal olive
#

@fierce holly have you tried attaching a debugger and setting breakpoints around the code youโ€™re concerned with?

fierce holly
regal olive
fierce holly
#

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 ๐Ÿ˜„

regal olive
#

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

fierce holly
undone coral
#

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

fierce holly
#

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

undone coral
#

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

fierce holly
#

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

undone coral
#

sure

fierce holly
#

I see, this is very helpful. Thank you for taking the time to look into it!

undone coral
viral flame
#

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/

fierce holly
lunar pulsar
#

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

echo timber
#

Is it alright to use multiple interfaces per script?

thin mesa
#

Yes

echo timber
#

Awesome, thx!

lunar pulsar
#

I think I've solved it, was squaring something that should not have been squared

shell grove
#

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?

gray pulsar
formal lichen
shell grove
#

I do use SetData already

#

ac.SetData(samples, 0);

formal lichen
#

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)

shell grove
#

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.

humble onyx
shell grove
#

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.

viral flame
#

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);
shell grove
#

I fixed the in-loop clicking by adjusting the sample length by the frequency

float[] samples = new float[(int) (44000 / notes[j].Frequency)];
viral flame
#

interesting, glad it's working!

shell grove
#

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?

viral flame
#

You probably need to calculate when the waves are 0, and choose some X count of waves to put in the sample list.

shell grove
#

Because now it stopped shortly before 0 and thus clicks

viral flame
#

Since you know the frequency, you should know the wavelength, which means you can tell it to store X waves as samples by length?

shell grove
#

the length is determined by how long the player holds the button

viral flame
#

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

shell grove
#

But that doesn't stop the player from releasing the button when the sample isn't finished, does it?

viral flame
#

hmm

#

Is it clicking when it stops or just when it's looping

shell grove
#

looping clicking is fixed

#

only when it stops it clicks now

viral flame
#

lmao of course, hmm, can you just fade it out really quickly as a hack? ๐Ÿ˜›

shell grove
#

hacky xD

#

That could work, but it would leave a bit of an sour aftertaste tbh

viral flame
#

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

shell grove
#

hrmmm

#

AudioSource.time is the playback position in seconds.

viral flame
#

It's dumb, but apparently thats what most of google says to do as well lol

shell grove
#

I wonder if I can't calculate the exact 0 point from there

viral flame
#

Makes sense yeah

shell grove
#

ehhhh

#

unity is too slow xD

#
yield return new WaitUntil(() => Master.timeSamples == (int) (44000 / notes[btn].Frequency));
#

This should technically wait till the sample is done

#

BUT this is only checked every frame, now Unity does not run at 44000 fps

#

frick