#archived-code-advanced
1 messages ยท Page 162 of 1
I could think their codebase is littered with unknown stuff they don't want public, like API keys or whatever
why would use 3d party solutions in public engine
could be true yes
Unity owns their engine. If they wanted to open source it, they could.
but again, make like Autodesk with Stingray Engine - they added support to C++ plugins with public headers
I think they would. Unity can't monetize services if people can fork their own engine and YEET themselves away from unity
why Cryteks and Epic Games then doesnt loose it?
Because it isn't an MIT level license
Yep, community would improve engine better then Unity themselves
exactly like it was with XRay engine
Maybe. Most likely not. Check out open source contributors for popular projects. Most contributions are from sponsor companies. Places hire people to contribute to open source.
My idea is what we make games, not mods, engine must be flexible enough to do whatever and how i want
It is flexible enough
Lol no
You can still do the same things you want just not in the way you are currently stuck in
Can i make custom placeable entity with custom icon in the world?
Yes
Yea
Lol
Just not in the way you would prefer to
Also, no longer #archived-code-advanced
Why?
Thats what i call not flexible
No engine is going to be flexible then
Source Engine? XRay?
I'm so happy you said this. I thought it. I thought it before you said it.
Because it's a discussion whether an engine is flexible or not, not advanced coding concepts in Unity
Basically, EVERY engine with open C++ code IS flexible, cuz i can just rewrite its part
We are discussing the interplay between the C++ elements of the game engine and how it interact with C#. What would you call that if not an advanced topic?
I'm not going to have a meta discussion about the topic of this conversation
That's not the engine being flexible, if you have to rewrite parts of the engine to work then that is a limitation of the engine and you're at that point developing an engine and not a game
Also you will not argue about performance loose with a bridge between (C++ <-> C#) native and managed code
its just poor dessign
Thanks. Please refrain from labeling topics as off topic when they are on topic.
we have luajit which speed MUCH better then C#
Scripting languages in engines are not just about speed
and Lua can just call any C function without performance lost
It's not poor design because it affords less experienced users to use the language at a higher abstraction than the low level C++ code
No one is making you use Unity, if you don't like how it works the ndon't
If u make game the most important things to you IS speed
No it's not
You can't talk about LUA in the same breath as discounting unity's use of C#
In 99% of the cases you don't need perfect performance, besides lots of cpp games have shit performance
They're the same architecture -- a byte code language on top of C++
Then look at Tarkov, guys was thinking the same
30 fps on RTX 3060
and 3950x
while we have 200fps with same config in BF5
how that was happening?
A Language does not automagically grant good or bad performance. It's up to the programmer
You're comparing apples and pears
I mean, there is a good solution
if you dont want to open C++ code, add luajit support
its speed only 2 times slower then C
and 10 times faster then c#
I'll just write asm, thanks
They have... instead of LUA they use C#. It's the same architecture
Wait... is this just an elaborate troll?
some would stay with C# and Burst which is not usable for projects like Tarkov, some will use lua which is perfect for that
i am not trolling, just arguing
@steel moss I have an idea... add a LUA interpreter to the C# space of unity.
Also luajit is compiled time, regular lua would be slow
oh no, that is bad
๐คฆโโ๏ธ
Why don't you make some utilities to make your life easier if you want to develop in unity?
That evolved into a meta conversation about how Unity isn't good enough, isn't it
Nope
If you want to use unity like source, make it happen. Hide the ugly unity bits behind your own abstraction.
Its about Unity Technologies does not support diversity
๐คฆโโ๏ธ
Yeah, so it's still meta, and not on-topic with this channel anymore
I still disagree with that sentiment. This feels very much on topic for this channel
I also am frustrated by the convo because it doesn't seem like you are willing to work with the limitations of this game engine. Why?
Thing is, if you don't like how Unity doesn't support diversity, then... just don't use it lmfao
Switch to Unreal or Source or whatnot
Or make an abstraction in unity that works like how you want it to
I dont use it, my company works with Source
Then why do you come complaining about it here
That makes no sense
It's like how I would go to a supermarket I've never been to before, and yell in that they suck because they don't have the same aisle arrangement as the one I'm used to
My sister is learning game dev with Unity and asked me for help, i tried... You know what happened next with GameObject inheritance
@steel moss why don't you teach her a game engine you are familiar with? Or... learn this game engine. You seem capable.
Did you get embarrassed when you couldn't do the basic thing in unity in front of your sister?
I think you're just trying to teach her Unity, but your other engine architecture experience is scrambling that up
She can just follow the beginner tutorials
Uh, its paid courses so it wasnt my decision, and i dont think 14yo kid can go with C++
Maybe let her learn unity on her own, and maybe later she can teach you
๐
what is this error supposed to help me ๐
restart the editor
ok thanks
There's probably another error or more in the description (usually is at least)
i've seen that error show up all on its own
there ain't, otherwise i wouldn't ask here
What version?
current LTS as thats all that I use (current as in, at the time it was the current LTS)
I only ever see it if I'm doing some dll stuff
yes, only happens when messing with external things
or on a new project with lots of assets/packages/libs added in bulk
how to make variable
jk
I have a pooling system of arrows, When I shoot an enemy the arrow sticks in that enemy and the enemy gets destroyed after a few seconds. This obviously also destroys the arrow stuck in the body. The problem is that when I get to that arrow again in my pool, I get a nullref because that arrow doesn't exist anymore? Ofcourse I could do a nullcheck but after a while my pool gets empty. I could expand my pool but that just delays the problem.
How can I detach my arrows before they get destroyed? Can I add a script to the arrow with OnDestroy method and unparent it there? I read that once Ondestroy is called you can't unparent it because it will get destroyed anyway? Any tips?
instead of parenting the arrow you could use a follow behavior I think
or you could detach before destroying
Thanks! But wouldn't that detach all children? I have a completely skinned character so if i detach children before destroying, all other objects would also be detached?
I'll look into that!
you can detach only the arrow
Yeah I should note that my arrow has no script attached to it. It is purely a visual gameobject. So the only way to do that is if I check each child in the parent, look for the name 'arrow' and then detach that object. But it seems a bit overkill or so I don't know.
But I just found that there is a parent constraint component made by unity so I'll check that first ๐
thanks for the help!
/ Check if caster has enough mana to cast the spell.
if (eventData.Caster.Stats.Mana < eventData.Ability.ManaCost) {
Debug.LogFormat("Invalidating {0}", eventData.Ability.Name);
eventData.Log.Add("Not enough mana!");
eventData.Invalidate();
}
this is bad
Why's that?
also, these methods are not IEnumerators / cannot handle player choices or time
or async
you probably have something of the form
spell:
do something
put an object in a list somewhere
time passes
player makes a choice
pop this object off a list somewhere
resume casting spell
this is also bad
No, I don't
Nothing yet, haven't got that far
got it
What's bad about what you quoted?
it should be knowable statically if something can be cast or not
mechanics that make something possibly not castable after you try to cast it, or vice versa, are cantankerous
you'll never write those
but the burden of that possibly happening will show up in a million places
The TryCast is mostly for UI
right, the UI should just show statically what can and cannot be cast
the player shouldn't have to try pulling a card in their hand / pressing an ability button to discover if they do or don't have enough mana
how would you render a green rectangle around the ui element if you don't know statically if it's castable due to mana?
statically means, you can just look at the game state, you would not need to push an event
and give other stuff the opportunity to run code
Fair point. I was thinking more in terms of silencing auras, things like that
a silencing aura would put an attribute / tag / whatever on something that says, "silenced"
so that you can resolve it statically
you wouldn't want a silencing aura to work like
model EVERYTHING as an event
the player tries to do something
run a bajillion pieces of code
\with uncertain interactions
one of those happens to be a silencing aura
it's a tries to do something event
check if there is an ...
touch a million things to prevent the player
\from doing something ...
it's really complicated
just
player cant' do something because it
has silenced on it
Hrm. That does make sense. I do intend to have silence auras give you a buff when in range
I like the idea of tags. Might do that for buffs
Just feels too coupled to me, sounds like pain
hmm but looking at your code
it is painful
Just me trying to understand an event bus I've never used
the events stuff makes stuff
because text in RGPs and magic-the-gatherings are "triggers"
and you need to do something because you do something else
Has anyone managed to get the logs from unity on iOS player that isn't built from your system and hence not attachable to xcode? Is it even possible? Google says no.
they're not a good way to model the whole game
Well, I need triggers and reactions eventually, like MTG
the best way to model the whole game is to just write it in code
write the code that does the thing
if you're like, well how do i deal with a player making a choice, that's what async (best) or IEnumerator (better) is for
because you'll find even in magic the gathering, which has 19,000 cards or whatever
that can be expressed in code
there's a lot of stuff they never do
so you never need something so flexible
and then, even with the weird stuff, it's better to special case it
because you might print only one card that does this 1 weird thing
you mean coming from someone who has a working multiplayer card game ๐
I have no idea where you pulled card game from, but cool
yes it sounds like an ARPG style game right?
Yep
i think you might have a very fixed number of reasons that an ability cannot be used - CANNOT_USE_ABILITIES, not enough mana, and no targets
which can be determined statically from the game state, and would not need to evaluate rules
and this will make your user experience better
whereas, if you permit a rule - really a triggered thing, this event bus - to decide if a player can use an ability
which sounds right doesn't it?
you will make everything way more cantankerous
if something needs to prevent an ability from being usable, it should shove CANNOT_USE on it
Yeah I'm not sure I'm gonna use the TryCast and Cast. Was more doing it because it seemed like a good way to get acquainted with the Event Bus
i think use the event bus idea as minimally as possible. introduce events and triggers to implement specific text
and make it async while you're still ahead
before you write all this stuff
because the game is going to get extremely painful to write if you don't deal with the fact that text doesn't deal with ticks but your game engine does
or whatever small unit of time you choose to do
What do you mean about the text dealing with ticks?
i'll write an example - is the game working like an ARPG / MOBA?
are those the kinds of abilities we're talking about?
Yeah
so let's say it's an ability with the text
Deals 150 damage over 3 seconds in a radius
Yeah, already have some of those. Definitely makes sense for async there
I just don't get what you mean about text
ideally, you'd want to implement this ability this way
protected override async Task<Ability> Cast(ICastingArgs castingArgs) {
var position = new PlayerChosenPosition(castingArgs).position;
var duration = new DOTTime(seconds: 3);
var frequency = new DOTFrequency(timesPerSecond: 4);
var damageLeft = new DOTDamageValue(150);
var targetingSpec = new RadiusTargetingSpec(position, this.radius, Filters.ALL_ENEMIES)
var result = await GameContext.instance.DoDOTDamage(
duration,
frequency,
damageLeft,
targetingSpec);
}
but new DOTTime and new DOTFrequency... would probably need to come from a factory
you want the text written the ability to appear in your spell implementation
and you want to deal with, what if the damage is buffed inside DOTDamageValue
because that's really complicated!
Ah, yeah, I'm doing something similar. Currently using coroutines as a placeholder. Using ScriptableObjects essentially as factories (from my understanding of the pattern) they actually create a new Ability object for each cast, so player stats, etc can be accounted for
DOTDamageValue looks like
class DOTDamageValue {
int textValue; // 150
int DamageToDeal(DOTFrequency freq..., duration) {
var unbuffedAmount = textValue / (freq * duration)
textValue -= unbuffedAmount;
return GameContext.instance.Buff(unbuffedAmount) ...
}
}
Luckily for me, no filtering necessary though
does this make sense?
you eventually want a piece of code to look like the text
you don't want it all abstracted away
if you can't find a piece of code that "looks" like the text, it's painful
it's really painful to turn text from ARPGs and card games, which are already algorithmic, into data structures
that's just a shittier C#
if your text doesn't look algorithmic, that's also bad!
that means the ability is written poorly
all of this stuff comes together
why async? because then you can use cancellation token
or any number of tokens
to deal with the bajillion ways something might be interrupted or changed
and do it in ther ight place
for example, it shouldn't concern that specific DOT ability if the player is silenced
Like what text? This is what I'm not understanding
DoDOTDamage should do the damage over time, but using a decorator (a function wrapping the damage over time rules) that deals with silencing, the player dying... etc.
the text written on the ability
Oh, the ability description?
I gotcha
this is already algorithmic!
you should write these first anyway
before you program anything
Yeah, I see what you're saying
at least a few
I already have them all, actually, so that's sorted
Mostly, anyway
You're right though, it is very helpful having all of that info ready before coding
Being able to skim through and see obvious requirements helps a lot
i would start with
what is the most comfortable way to putting the text into code
it's probably not by dragging and dropping stuff into the unity inspector
a lot of people think it is
for some reason
i am personally most comforted by finding functions that say what the text says as closely as possible
you will want to "factory" the numbers and effects in the text, as types, and use the implicit/explicit casting to make it easier to use
so instead of
var damage = 5
you definitely want
DamageValue damage = GameContext.instance.CreateDamageValue(5);
Yep, this is why the placeholder coroutines for now. Will probably be trying out UniTask for this project soon
async can be painful because it has this cancellationtoken thing
that you gotta really master
because a ton of gameplay will interact with it
Makes sense
you want to factory these values because, for example, they may need to be buffed and have references to state, or because you might want to attach a description to it for a tooltip, etc.
Exactly, yeah
okay cool
Well, cool. Thanks for the advice. Will keep it in mind. Gotta go though. Later
Im working on a 2d top down game. Im trying to implement solid principles i just learned. Is this good practice
you can change the camera speed but not sure if that works for the zooming
I'm trying to do some digging to find out if there's a solution for my issue. I just want to disable certain hotkeys so they do not work in play mode.
what a "combat system" has to do with colliders
In my case I don't want Ctrl+S to work because so many games use that with crouching + walking backwards
and if I do it, it just spams save errors in play mode
do you know what virtual methods are?
seems that chasing solid is premature
hey im trying to update a mesh but im wondering if theres a way to update a part of a mesh quickly without resending the whole mesh back to the vertex buffer
Maybe later i want to melee attack by layer or something else i can create meleeattacklayer and implement IMeleeAttack and inherit combatsystem. Every melee attack script needs attackdamage layer and position. Thats what i was thinking
combat system implies a system
thanks
this is not a system this is a component of some kind with a specific purpose
start with single responsibility principle, an attack is not a collider
a collider is a dependency of an attack
study virtual methods
drop the idea of learning solid, its useless to you at this point, focus on simply writing logically cohesive code
What I do is wrong with meleeattackcollider script? I am aiming for dependency injection by creating it
as I said before in the future of this project maybe i would like to attack by layer
why does List.Contains always return false?
try to put yourself in a place of someone that has to answer your question
wdym?
follow the logic :
- It actually does work for literally everyone, as it always did.
- If it doesnt work for you, you dont provide any information so assume people are telepaths
so, how can anyone answer your question
why the hostility?
also there isnt more knowledge needed. if i have a list and i do list.contains(obj) it always returns false.
Then obj must not be in your list. Do you have an example? I use it all the time
there isnt more knowledge needed
my boi over here bein hostile
Tbf your question was crap
you can keep trying to paint me hostile, or you can agree that your question was unanswerable and finally provide code
It's obvious that your List does not contain the thing you want, the method is working as intended
With no more info, that's the answer
Some people learn their lessons the hard way
sounds like reddit in here
Because reddit people like to act all logical? Programming is about logic, nothing strange that people operate on it.
The only reason that .Contains(..) would not return the object, is if you have overridden the Equals(..) method for the object and did it wrong/in some way that they don't equal
If you don't know what it is then it is safe to say you didn't override it ๐
Try adding the object before checking if the list contains it. That will tell you that if the Contains(..) method is finding the object or not
that isnt the issue. im checking if a list has a string before it adds the string
but it always returns false
Without providing any code, there is very little anyone can do to help
There may be something that you think is inconsequential so omit, but is actually very important
it sounds odd, but im not a big fan of showing my code cause it sucks
Your choice, but without showing the code you aren't going to be getting much help from people on the internet (for the reason stated previously)
well, thanks anyway
@raven jewel Yeah, and that is the reason why you called me hostile, server non useful and compared it to reddit, its not because we are what you say, its because you are defensive or have another reason that you don't reveal.
And its ok, no judgement.
my point was more to your phrasing and such. for instance, i thought mantistobboggan and mech were real nice and professional while you came off as something stuck up your ass
and i still get that impression because you still are on about it
I am just blunt. I am voicing whats on the mind of most.
so did mantistobboggan and mechwarrior99 and yet they were nice about it and not stuck up
but i cant teach you manners
You are doing it again, my hope is that you see that its simply innefective.
When you get/set components from game objects, it's a form of dependency injection.
sounds incorrect, provide an example?
I like the way this code looks. It's good to practice SOLID but try to know why you apply each principle. Don't do something for the sake of doing it as a rule of thumb. That said, continue the practice as it'll make your code have better qualities.
Just checking... what is your level of familiarity with dependency injection? I'll use that in my explanation.
I can write my own DI container
Excellent. If you know that, then you should be able to reason out how accessing components on a game object is a form of DI
sounds incorrect because the gameobject here acts as a local service locator and not an injector
Thank you so much! I'll keep practicing ๐
That's getting a bit into the weeds into implementation details, lol.
those are different principles
o...okay.
Anyways, yea when I realized that get/set component API was a form of DI it really cleared things up.
Well. Shit. @plucky laurel is right. Hell yea, I can improve my vocab. I've been chunking both concepts in the bin of "DI"
Although, I suppose to get real technical. SetComponent is DI and GetComponent is SL
i also spent some time thinking and you are right in some aspect, you can use gameobject as di container, because it has type resolver,
however even if we think of it as container, as soon as you do
void Awake(){
GetComp<IFoo>
you are coupling the object to the container, which is volation of the ioc, which makes it not di
Yea... It doesn't fit any definition very well. I think that's a side effect of the weirdness of game programming, to go on a limb. ๐คทโโ๏ธ
I'm a programmer interested in writing tests for my code. For me, I just see a game object as a weird way of injecting mocks or spies into a monobehaviour for analysis
is there any framework for that?
Like... honestly I wish I had read a good analysis on what exactly a game object is in relation to DI/inversion of control. I haven't really found one (which is why I enjoy convos like these!) so I am left to synthesize knowledge from other sources (DI:principles, practices, and patterns) and work my brain into making things make sense
I use vanilla unity testing tools and build my own abstractions around it.
I haven't spent time noodling on how to add nuget dependencies to a unity project. I've seen people version control DLLs in their projects which isn't an option for me because I work publicly.
Writing a mock or a spy or any test fixture is pretty easy. When I do have the benefit of nuget, I usually reach for NSubstitute.
Is this answering your question? I may be missing the mark and wanted to check
anyone have experience using unity command line or a ci/cd within unity particularly regard arkit
will literally pay you to help me solve my problem lol
Yeah i was thinking about nsubstitute, but its interface/virtual only, so got me thinking if writing something that generates any mock from any class jit and understands unity specifics, gameobjects etc, wonder if something like this exist
this is a rabbithole, ill cease my mental gymnastics
Good question. That kinda reminds me of what Faker does.
You seem like someone who has considered program design before. Question-- what is your philosophy on the right levels of abstraction?
I've had to tune myself over time (and still do) to choose correct abstractions for the task at hand.
I usually abstract too low level, which grinds productivity to a halt.
I use game.ci for my projects. It's amazing! I haven't used unity's AR kit yet, though.
hmm im currently set up in Jenkins already
@alpine adder the creators have exposed docker containers for consumption, though that's more advanced (especially those w/o container knowledge)
One sec, getting a couple URLs
abstracted myself into a corner many times with painful refactors, the opposite is also true. I cant outline any concrete guidelines i follow, i think my brain factors in things like future points of extension, volatility of the thing, duplication, complexity (if i dont abstract it here, how easy it will be to abstract later, if easy then whatever), taking designer needs into account, probably more factors. But since i dont enforce it on myself and in none of my gamedev commercial experiences ive encountered any project big or small that adhered to something completely on the level FizzBuzzEnterpriseEd, i feel pretty good if time investment/tech debt/KISS are balanced. @regal olive
Docker hub link: https://hub.docker.com/r/unityci/editor
Here's a link to one of the GitHub actions (read for figuring out how to use): https://github.com/game-ci/unity-builder
Here's the game.ci website. This is where I got all these link. https://game.ci/
yeah im on the side - weight all factors and decide is it really necessary, basically.
@alpine adder using bit bucket/Jenkins shouldn't be a huge barrier. As long as you have the CI/CD webhook starting Jenkins jobs. You'll have to add a step to run some docker commands, based on code you can reverse engineer from the GitHub actions.
It'll take some translation! I recommend getting started by building your project locally using docker.
gamedev is such a mess generally
I am not surprised by this. It seems like getting the right level of abstraction is an art. It's based on experiences, ha. The book "the design of everyday things" has got me thinking about abstractions and good design.
Preach! I have a collection of axes I like to grind when I have a listener and I feel like complaining
Oh yea, game.ci has a discord server too (link in their website). I'm sure they would love to help if you reach out
when i encounter people who are deep into dod/verbose ecs i feel at a loss, i feel like im stuck on oop/"a thing" thinking
think i have to invest time into low level stuff at some point
Iโll have to check it out
Im sure people on that discord could help out in general
This video helped me conceptualize OOP and right levels of abstraction
Explore DDD 2019 - Denver, Sept. 16-20
Object-oriented languages have opinions about how best to arrange code. These opinions lead OO to naturally offer certain affordances. Just as round doorknobs expect to be grasped and rotated, OO expects messages, polymorphism, loose-coupling, and factories. The key to creating intuitive and maintainable O...
Maybe less on the docket and server side stuff
But we all have to code in unity command line for this
And create a build file in editor
@alpine adder what are you trying to do, in a couple sentences?
Enable ARKit through the manager plugin api so that when we build for iOS ARKit exists and is linked
here is a thread i made
There are C# as a build file solutions
Like Cake and Nuke
You can get pretty much completely C# driven pipeline if you want to
https://game.ci/docs/github/builder#buildmethod
Here is game.ci calling out how to point it to a custom static c# class.
yup thats exactly how im doing it
we call the static class or method from the buildscript in the editor folder
its the plugin management code to turn on arkit thats not working
I wonder... When you import that plugin via the package manager locally, is there an additional set you have to do?
Example: when important text mesh pro, you then have to unpack it into your project. Is there a step like that for ar kit?
hmmm
not that im aware of
the step is to click the little arkit button support in xr-plugin-management
which is what the code in the thread aims to do
Okay. If you don't click that little arkit button locally after installing the package I wonder if you could recreate the issue on your local machine.
By the way, everything works when you build locally, yea? I figure yes but I also don't want to assume
yes. if i don't click the little button i get the same errors
but if you look through the build script and say re-open the engine after running the build script it does look like the little button is enabled
although it doesn't seem to act like it
Gotcha. Here's what I would do. Assuming this package has at least some parts open source, I would reverse engineer whatever C# script backs whatever that button press represents
Let me see if arkit source is on unity's GitHub
Hmm, no luck. I'm on my phone so it's harder.
Reading the AR kit docs (https://docs.unity3d.com/Packages/com.unity.xr.arkit@4.1/manual/), it looks like it has a section on build settings. Idiot check -- is that something missing from the build?
nope thats exactly what im talking about
the code you see above is doing what it wants through the script
but thats not whats working
and hense the errors
This might be the source code: https://github.com/U3DC/Unity-ARKit-Plugin
The editor script that defines what all happens should be in there. My hypothesis is you may be missing a call to something in your build script
Shoot me over a screenshot of that button and I can try finding the file
@regal olive thanks for all the food for thought
maybe code is in here
are you trying to automate a build of an ARKit app?
i'm confused why you have to do this at all
i build an android ARCore app and ios ARKit app from the codebase and i don't have to touch this stuff
the build script just works with BuildPipeline.BuildPlayer
it is an app that has arkit
i don't understand why you have to "turn on ARKit" programmatically
what am i missing
if the checkboxes are checked in the editor it should just work
are you not checking in some asset files or setting or something?
are you trying to build this not on a mac?
i have build automation working just fine
i'm using com.unity.xr.management@4.0.1
shouldn't it be checked already?
so im building it on a server. I check the box manually but still have issues for some reason
so i wrote this code to do it automatically
as a fail safe
i don't understand
i am also building it "on a server"
i get what your goal is
but what is really the thing you're working around here
because if it's checked, it's checked
i still get linker errors though
on a linux build server?
have you tried downloading the project and running it on this mac mini
opening the project
yup
are you using BuildPipelines
but going through my script it has linker errors and arkit does not generate in xcode
im using jenkins. but the build script which is what unity handles is roughly the same
i think this checkbox is a red herring
i'm saying are you using UnityEditor.BuildPipeline.BuildPlayer
correct
BuildReport buildReport = BuildPipeline.BuildPlayer(scenes, targetDir, buildTarget, buildOptions);
have you tried building this on unity cloud build
I have not. at least not in a year
your build script can be really simple. is it? you sort of have to get rid of all this other stuff
i would try making a super simple script
and try running it on unity cloud build
and see what happens
jenkins is 
that is true
lol
the original use for Jenkins was so we could run builds when creating prs
there are a bajillion things that could be wrong with a jenkins build agent
unity cloud build only runs after a pr goes thorugh
i don't know. is this a lightship project?
we have others i set up that are
is this the only one using ARKit?
also, are your development machines all macs?
and when you open the project on the mac mini, does it make changes to any files in the tree?
you might be .gitignore -ing a file that you need, that's generated by the editor
i am leaning on this being a smaller issue than a bigger issue
it sounds like you're doing everything right
i think maybe you just make well-named branches for unity cloud build and work aroun dit
like staging-1 staging-2 staging-3 ...
so it goes.
hmm we develop on windows mostly which is why our server is a mac. the tree idea is interesting i havn't checkked yet
and yeah ill see what cloud build does
maybe its worth the switch over
"well there's your problem"
it's not really possible to develop ios apps on windows
it's a bankrupt idea
have yout ried building a unity xr sample
with your script?
It's for CI/CD
Jenkins is a standard in the CI/CD industry. It's a big name. A lot of businesses use it. I prefer github & gitlab actions myself, but I've set up a jenkins server in a docker container before. I enjoyed watching how it evolved.
it's not really possible to develop ios apps on windows
I'm on my desktop now. I'm going to test this hypothesis using the game.ci docker container. I hypothesize this is correct, and one would have to use a OSX based image to build the production artifacts. We shall see for sure shortly
try some arkit for me ๐
Hey anybody know if there's a way to subscribe to Unity Roadmap updates? I used to subscribe to the old rss feed, but they don't seem to be updating it anymore
Not really a Unity question, but there's some bright folk in here, and this is probably one of those "fun" problems that.. I can't seem to dream up an elegant and time-complexity fast solution for.
I have a list of missions in a "bag". Each has a weight (integer, typically 100-200). I'd like to draw an item from the bag randomly where the odds of drawing out any given item are the item's "weight" divided by total weight of the bag. My solution is not good, but hopefully illustrates the problem:
(In this example, AvailableMissions is a dictionary<guid, int> where the key is just an identifier and the value is the integer weight.)
int weightTotal = AvailableMissions.Sum(x => x.Value);
Guid drawThisMission = Guid.Empty;
foreach (KeyValuePair<Guid, int> kvp in AvailableMissions)
{
int thisRand = NumberUtils.Next(weightTotal); // 0-999 for 1000 total weight, eg.
if (thisRand < kvp.Value)
{
drawThisMission = kvp.Key;
break;
}
weightTotal -= kvp.Value;
}
I presort the bag from highest-weight to lowest weight to minimize the iterations here on average, but obviously this is a pretty poor solution. I'm not even sure if it's correct.. It seems to be?
A quick google yielded no obvious algorithm/heuristic for this, and yet, I feel that in the game dev world this has to be a solved problem. TIA.
Hey, so I am converting a class to a byte[], send it over the network and convert it back to the class on the other end via marshalling. I am now facing problems sending arrays. I tried following attributes for the array:
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
[MarshalAs(UnmanagedType.LPArray, SizeConst = 3)]
[MarshalAs(UnmanagedType.ByValArray)]
[MarshalAs(UnmanagedType.LPArray)]
ByValArray crashes the receiving end, LPArray gives following error: Structure field of type Int32[] can't be marshalled as LPArray
Code references for the marshalling functions and my full class im sending:
[NetworkPacket, StructLayout(LayoutKind.Sequential)]
public partial class SamplePacketData : INetworkPacketData
{
public float Time;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
public string Name;
[MarshalAs(UnmanagedType.LPArray, SizeConst = 3)]
public int[] Test;
public string Testing;
}
// Marshalling
// TData = SamplePacketData
static byte[] StructToByteArray(TData obj)
{
int len = Marshal.SizeOf(typeof(TData));
byte[] arr = new byte[len];
IntPtr ptr = Marshal.AllocHGlobal(len);
Marshal.StructureToPtr(obj, ptr, true);
Marshal.Copy(ptr, arr, 0, len);
Marshal.FreeHGlobal(ptr);
return arr;
}
static void ByteArrayToStruct(byte[] buffer, ref TData obj)
{
int len = Marshal.SizeOf(typeof(TData));
IntPtr i = Marshal.AllocHGlobal(len);
Marshal.Copy(buffer, 0, i, len);
obj = (TData)Marshal.PtrToStructure(i, typeof(TData));
Marshal.FreeHGlobal(i);
}
Nvm, im stupid, i forgot to set the MarshalAs for the string after the array, which crashed the marshalling
Why I get this error?
error CS0236: A field initializer cannot reference the nonstatic field, method, or property Settings.PatcherSettings.environment'`
because you are trying to access something that isn't static in a static context. Assign the field in Awake/Start. Or ask in #๐ปโcode-beginner
because you cannot reference Settings.PatcherSettings.environment in a field initializer
thank you so much
IEnumerable<int> CumulativeSum(this IEnumerable<int> items) {
var i = 0;
foreach (var x in items) {
i += x;
yield return i;
}
}
var weights = new List<int>() {20, 50, 10, 100, 30};
// O(n)
var ranges = weights.CumulativeSum().ToArray();
var total = ranges[ranges.Length - 1];
var rand = UnityEngine.Random.value * total;
// ๐คฏ O(log n) lookups
var i = ~normalized.BisectSearch(rand);
// O(n)
weights.RemoveAt(i);
this way you do not have to sort anything, so it's O(n) instead of O(n log n)
once you've computed the weights once, you can draw in O(log n)
this is fine, because getting the probability directly by calculating the multinomial hypergeometric has a combination in it that is O(log n) anyway
lol
i just looked this up
to see if it was possible to do this faster
i don't think you can
I will have to dissect that a little bit further - I think that's where I was going as well, and when I realized I was reading some research papers and code written by donald knuth I knew I was pretty far down the rabbit hole
this one is pretty simple
in the grand scheme of things
you eventually need a cumulative sum
so it will be no better than O(n)
A couple of problems - I will often be pulling items out of the bag, and also incrementing weights (they're not fixed), so I may potentially lose savings on the draw operation by the .. uh.. initial operation
but since a cumulative sum is sorted, you don't need to sort
that's okay
you can't beat O(n)
that's fine
I saw something about the binary search tree population
you can sort of optimize the cumulative sum. but it will still be O(n)
i wouldn't sweat that part
Yeah.. I worry about this a little bit because I think the game designers intend to have several hundred missions so... performance might actually matter
i mean you can optimize the cumulative sum even after removal
but it's not worth it
it wont' matter
because it's randomly chosen
so it will still be O(n)
O(n) for the draw operation? or the population operation?
O(n) is if you calculate the cumulative sum every time
whichi think you have to if you always remove it
I thought there was a method here with relatively modest space complexity that could do the draw operation in O(1)
hm... I feel like there has to be a nifty way to recalc in less than O(n)
I wonder if I could do something really fast in less-than-perfect manner
no
you are already doing O(n)
because you're removing from an array
you can remove from a map, sure
dictionary removal ops are O(n)? i thought they were O(1)
hm..
my brain is too tired to search for better i think
and TBH this is getting into the realm of .. "if i try to optimize this in a manner I don't thoroughly understand the bugs that arise are going to be very difficult to find and fix"
so I perhaps should just leave well-enough alone
lol
there's no cumulative sum update that is better than O(n) in the general case!
it's impossible
Kind of an interesting problem I am facing. I was wondering if there is a way for an object (gun in this case) to point to what is in the center of the main player camera, because I thought it might be an interesting effect for my first person shooter. I've drawn up this diagram thing to help explain that maybe I could use angle D to adjust the guns rotation, but I have no clue how I would go about doing this. The gun is a child of the Main Camera.
๐ you have my seal of approval
lol
i'm trying to read it ๐
i was annotating it
lol
okay
you are maybe overthinking this
you can just do
transform.LootAt(worldSpacePositionOfCursor);
transform.up = Vector3.up;
i think i can do better than O(log N) in recalcing the weighted sum, btw, IF i accept less than perfect precision
but I don't know that I can prove this, just a gut feeling, and i'm not sure what the loss in precision would be
i guarantee you you'll violate some law of physics
if you could somehow touch N values with less than N touches
we're hiding a sort in there
that's why it works
you're beating O(n log n)
cumulative sum gives you an array of sorted values
any other optimization would require sorting the weights first, which is O(n log n)
so cumulative sum is already the hottest in town
cumulative sum giving you sorted values lets you use binary serach on the lookups
true but my operations are always exactly "remove one item" or "add one weight to every item" and i feel like those could be .. cheated somehow
you can do
remove i...
update all items i...n - 1 with -= value[i]
but it's still O(n)
and it DOES affect the probabilities (logically)
because you removed something out of the bag
so you can't just be fuzzy about it
hm
that makes sense, but i'm still going to think on this overnight or in the next couple of long showers
you can't just skip it because then you'll reroll on aveage the number of items you've removed
which adds up to... O(n)
no dude you will be trying to bend quantum spacetime
haha
but i am juts wondering how i can fuzz the data or sorting to get "good enough" randomness at vastly improved performance
like imagine the degenerate case with an infinite number of items with equal weight
if i draw one out, recalculating every item in the array is infinite time
and yet the odds of each/any of them being drawn on subsequent draws is virtually the same
you'd have to know the sum of the weights anyway
so.... there seems to be some way to get to about that performance without recalcing
once, yes, but not on every draw (unless the randomness needs to be exact, which it doesn't)
it will always be O(n)
you can reduce your precision of the weights, but you'll only get an improvement if you reduce the precision by O(log n) at least
the position?
such that at least n - log n elements or more go from having different weights to the same weight
ah
do you see how that is a big cheat? that's saying you want to turn n elements into log n elements
so you can go from
10 11 9 10 3 5
to
1 1 1 1 0 0
reducing the precision
and now, that appears to be
1 1 0
does that make sense
not sure i follow..
but I can't chat atm - just putting kids to bed
(and then i gotta hit the hay myself)
but... I think I'm understanding enough to see that i'm not going to really improve on the example above
the point is, you can do "make these items be the same", and roll twice - once to select from a reduced set of items, and then another time within items of the same weight
that's the fuzzy part
and that smarter people than me have spend a lot of time on this uh.. CDF? cumulative distribution function?
but in the process of fuzzing it down, you will have visited every item!
the CDF of a multinomial hypergeometric is really expensive to calculate
3 F 2 is really expensive to calculate
guess what you have to do to calculate 3 F 2? a sum*!
it's unwinnable
I am trying to recursively go through every child object and save & set their material to a single new material, but when this runs- all the children object seem to just get a generic new material instead of the single one I make at the start with fullCoverageMat
public void SetShader(Shader newShader) {
fullCoverageMat = new Material(newShader);
ChildInChild_SetAllMats(transform);
}
private void ChildInChild_SetAllMats(Transform parent) {
foreach (Transform child in parent) {
Renderer rend = child.GetComponent<Renderer>();
if (rend != null) {
storedMats.Add(child.gameObject, (Material[])rend.materials.Clone());
int matCount = rend.materials.Length;
rend.materials = new Material[matCount];
for (int i = 0; i < matCount; i++) {
Debug.Log("Setting material");
rend.materials[i] = fullCoverageMat;
}
}
ChildInChild_SetAllMats(child);
}
}
@misty glade even if you binary tree sorted the cumulative weights, then tossed weighted coins on your way down the tree
deleting could wind up making the tree height n
its' unwinnable
Does anyone have any idea why rend.materials[0] = fullCoverageMat, may not be working as expected?
materials is a copy of the array
@misty glade you can use this
this will be O(n log n) once you've deleted every item, which is as good as you will do.
this beats my O(n^2)
you won this time @misty glade
Yeah... I kind of figured that would be an issue later I also need to solve. But currently, a little stuck on just setting the materials when I set renderer.materials to a new array w/ each material set to a single reference of fullCoverageMat
I'm not sure what you mean. The issue with your code (without the full context) is not re-assigning the material array back to .materials, you need to modify the copy and assign it back.
I haven't gotten back to the resetting of materials, but this is the entirety of messing with the materials
public void ResetMaterials() {
ChildInChild_ResetMats(transform);
storedMats = null;
}
private void ChildInChild_ResetMats(Transform parent) {
foreach (Transform child in parent) {
if (storedMats.ContainsKey(child.gameObject)) {
Renderer rend = child.gameObject.GetComponent<Renderer>();
rend.materials = storedMats[transform.gameObject];
ChildInChild_ResetMats(child);
}
}
}
public void SetShader(Shader newShader) {
fullCoverageMat = new Material(newShader);
ChildInChild_SetAllMats(transform);
}
private void ChildInChild_SetAllMats(Transform parent) {
foreach (Transform child in parent) {
Renderer rend = child.GetComponent<Renderer>();
if (rend != null) {
storedMats.Add(child.gameObject, (Material[])rend.materials.Clone());
int matCount = rend.materials.Length;
rend.materials = new Material[matCount];
for (int i = 0; i < matCount; i++) {
Debug.Log("Setting material");
rend.materials[i] = fullCoverageMat;
}
}
ChildInChild_SetAllMats(child);
}
}
every time you call rend.materials it makes a copy
so you are assigning an empty array to the renderer
oh, oh ๐คฆโโ๏ธ
and then iterating and making matCount of copies, each with only one material assigned to them
So my initial problem is that I am using a copy instead of source
Why is my coroutine doing this? I was having the same issue with Async the force value is jittering. maybe the issue is the lerp? pls @ me
With pointing that out, I got setting the materials working now, thanks.
Make sure that you use float and not int
The truncation with the int is intentional if that what you mean
I suggest using Mathf.RoundToInt() in your division comparison.
You aren't going to be able to do much generics (at least what you're wanting to do) https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/types/anonymous-types#:~:text=Anonymous types typically are used,more public read-only properties (type T)
put the ref argument in a local variable
? I'm not sure wdym by that
hm, what if I do unsafe
and instead of ref I pass pointer
will that work?
assuming I never write to that struct
I only read from it and change it's internal fields
bruh
Can't do unsafe because structs are unmanaged.
And try without an anonymous delegate, use a method that has a ref parameter.
private void Register<T>(ref T act)
{
T captureAct = act; // this is a local variable that can be captured by the delegate closure
Action performed = () =>
{
captureAct.pressed = true;
};
}
but those changes will only be applied to copy
not to referenced struct
Thatโs the whole point of a closure
if you donโt want that, donโt use closures or ref
I'm simply trying to reuse code here
as otherwise I'm forced to write same method for each action
it worked like a charm when I didn't have to register callbacks sadkek
private static void UpdateAction<T>(ref T action, ref bool state) where T : struct, IInputAction
{
if (action.Active)
{
if (state)
{
state = false;
action.Active = false;
}
else
{
state = true;
}
}
}
this works for every action
you could use regular methods
wdym?
oooh
damn
I can simply use same struct
lol
damn it, I'm pepega
ok, it still leaves me with inablity to use ref in anonymous
private unsafe static void RegisterAction(ActionComponent* action, InputAction input)
{
input.performed += _ =>
{
action->Pressed = true;
action->Active = true;
};
input.canceled += _ =>
{
action->Pressed = false;
};
}
hmm, I wonder if it's safe
Then use a method instead of a delegate, for the 3rd time
it doesn't matter if I use method or delegate, it's still be anonymous
I can't pass struct reference to that method
without writing code for each of those structs
Yeah, and the parameters wouldn't match anyway
but, maybe it'll work with pointer
Pointers are unavailable for unmanaged types (structs)
But, why a struct in the first place anyway?
Ah, I see
I'm afraid it's not possible then
Also, as regular structs can contain managed types, I would suggest changing the generic constraint from struct to unmanaged
you mean I can't get pointer to struct?
No, because structs don't live on the unmanaged memory (the heap)
hm, I believe it's not true
because I saw some Unity code
I actually used some unity code
that uses struct pointer
ahem
Unity.Physics? Now that's a namespace I don't know about
They're not the same as the regular Collider component
From UnityEngine
No idea then, good luck!
What's a good way of making something in unity that has super poor performance characteristics?
I'm instantiating, waiting a frame, deleting, and doing that. It's the exact opposite of object pooling. The GGC kicks in after a while and I can see it all happen in the profiler. This works but I'm sure there are plenty of other ways.
I'm trying to flesh out common ways to make under performing unity software. There aren't many guides since most want to steer folks towards good performance. I want to break things
Using Find operations each frame, on multiple objects will be a sure way to kill performance.
Are you trying to find a list of common/realistic things that hurt performance, or just trying to introduce bad performance as a demonstration? For example would Thread.Sleep do it for you?
im back
calculate some mandelbrot set
or find a prime
Common/realistic/unusual ways of tanking performance
@undone coral I'll still need (want?) to wrap my head around the implementation for this and implement it in C# anyway, but this looks like exactly what I was looking for. O(log n) worst case!
My python is a fair bit rusty as well (embarassed to say)
using lots of reflection, runtime types and logging everything with full stacktrace in update while writing that log to disk
Heh, no way reflection is that bad on performance.
I'll see though!
you'd be surprised
I am trying to do a cone of area damage. My parent transform does not rotate and it is 2D, so I handle the rotation on a child gameObject. Though I have noticed that local directions are a little weird. I drew a line with "transform.TransformPoint(Vector3.forward)" and the line works as intended. However, calculating the angle seems to not work properly:
Transform target = col.transform;
Vector3 targetPos = (Vector2)target.position + (target.GetComponent<BoxCollider2D>().offset * 2);
Vector2 directionToTarget = (targetPos - transform.position).normalized;
Debug.Log("Angle " + Vector2.Angle(transform.TransformPoint(Vector3.forward), directionToTarget));
If anyone knows a better way to do a "cone" of damage on a local object or if I am doing something wrong, that would be great! I am trying not to enable and disable a collider a bunch of times and would rather do a OverlapCircleAll and check the angle as I am trying to above
transform.TransformPoint(Vector3.forward) is similar to just transform.forward
And neither of those really make sense for a typical 2D game
typically "forward" in 2D is either transform.right or transform.up depending on how your sprite is drawn
transform.forward is typically "into the screen", along the z axis
Yes thats what I thought too, but my object must be rotated weird or something to do with the local directions. Ive been trying to switch to dot since that seems to be how most people do it. I seem to have got the below code working:
float cosAngle = Vector2.Dot((inputPoint - (Vector2)this.transform.position).normalized, this.transform.forward);
float angle = Mathf.Acos(cosAngle) * Mathf.Rad2Deg;
Debug.Log("Angle is " + angle);
return angle < 70;
What exactly are you trying to do?
Show a screenshot of your object in the scene
selected, and amke sure your tool handle rotation is set to "local"
For sure, one sec
And I am trying to do an aoe damage within a certain angle.
Here is my player. The purple particles rotate to follow my mouse position. The cyan line is the transform.TransformPoint(Vector3.forward) and red line is transform.right. That triangle collider is where I want the damage to be. It seems like the new dot function that I added is working as intended
The red line transform.right barely moves, it just moves left and right a tiny bit. Even doing full circles around my player with my mouse
the fact that the blue arrow is to the right and the red arrow is down is indeed weird
red should be to the right
and blue should be into the screen
you should fix your object hierarchy and rotations
(I'm assuming you're in 2D mode?)
Yes I am
Hiya, quick question, with the SpriteRenderer component, how does it allow my to select a file from the project files? more acurately, where would y'all say is a good starting point for researching that whole thang haha, thanks! I need to use asset files so that I can do a preset style function fyi, thanks again!
You put an image file into your Assets folder anywhere, click on it to look at its import settings, and make sure to select "Sprite (2D and UI)" as the texture type
Then you can drag and drop it into your SpriteRenderer or UI Image component
Read more here https://docs.unity3d.com/Manual/Sprites.html
oh sorry, i should've said, i mean so that I can do presets for like, weapon damage/effects, i used the sprite renderer as an example of selecting an asset from the projects, my bad!
lemme show you my setup one sec, i'll thread it so as not to spam
Hi folks. I created a 2D level editor for my students (for NES Metroid and Zelda levels) a couple years ago. One of the things it does is export a PNG of the entire map via byte[] bytes = Texture2D.EncodeToPNG() and File.WriteAllBytes(path, bytes);. This worked very well last year and the year before, but now, when I run this in the Unity Editor on macOS, the debugger runs through this code fine, but then my entire Mac freezes (apart from the mouse), and I must restart. (It appears to work fine on Windows.)
My assumption is that this is due to the macOS's new restrictions on accessing the drive and that somehow Unity is restricting me from seeing the message where macOS is asking if it's okay to access the drive. If it makes a difference, I'm attempting to write to the Desktop in my own user folder. Alternatively, I would be happy to copy the image to the Clipboard, but copying an image to the Clipboard also seems to only work in Windows.
If any of you have suggestions or thoughts on the issue, I would really appreciate it. Thank you in advance.
It might be where the file is being saved if the current user has the correct permissions to perform full RWXC abilities there or not. When you debug where does it get stuck at in the code?
As in when does it become non responsive
could anyone please help me? i am trying to calculate the angle of reach for an artillery gun, but for some reason it only hits the target at around the 60 degree mark, and below/above that it shoots short or too far :c. Here is my code: https://pastebin.com/yJEZiC3k
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
im curious how old are yall
what does this have to do with advanced coding
Bot or troll shrug.
if you delete every item it's O(n log n) overall
try writing to a path in the project folder first
in fact, just doing everything but writing the file will tell you if it is a permission level issue.
Strangely, it completes all of my code in the save function and then becomes unresponsive, which leads me to believe that writing to disk is an asynchronous task. So, in this code (https://pastebin.com/0hR6eDf2) the debugger exits SaveTextureToFile() before the computer halts.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Disc writes are always async depending on when then OS finishes the task. That's why we used to have the save to eject stuff for USB
(Sorry for the delayed response. I was taking care of my toddler.)
Yeah, that's what I was thinking. Thank you for confirming. ๐
Will this still be the case with the asynch file operations? My assumption is that macOS is supposed to ask me in a modal dialog box whether it's okay for this app to write to the Desktop, but I'm never seeing the dialog box, so my computer is frozen waiting for my approval to a question it's never showing me.
Windows won't prompt you it will just fail to create a file or edit
Do a check if the file exists before hand maybe? I'm not too familiiar with MacOS I just compile code there for iOS
Thanks. Here's the crazy thing: the PNGs I made are actually there! My computer crashed and froze, but upon restart, the files exist. I don't understand this at all. :/
anyone? :\
I'm sorry. I don't know what you mean by "angle of reach".
Projectile motion is a form of motion experienced by an object or particle (a projectile) that is projected near the Earth's surface and moves along a curved path under the action of gravity only (in particular, the effects of air resistance are passive and assumed to be negligible). This curved path was shown by Galileo to be a parabola, but ma...
You are asking why some other code has a different result than this code I assume and I can't tell what you are doing. You may have drag turned on
in simple terms the angle the gun has to shoot at to reach the target
You may have other things influencing the trajectory
all drag is off
I gave up trying to read between the lines on what you posted. Narrow it down to a couple lines instead of an entire update function
angleFinished = 2 * Mathf.Acos(angle);
You set g = **โ**Physics.gravity.y, which will make g a positive number. Is that what you want?
I'm confused by gravity * distance. Gravity works over time, not distance.
One way to think about it is that you want velocity.y + (gravity.y * time) to == 0 at half the distance to the target (if the target height is the same as the firing height).
right
So, any time gd > v^2, the function doesn't work, right? Meaning that there is not enough velocity to ever make it there.
yup, doesn't seem like it cares about that though
Your arcsin and arccos functions will probably throw an error.
not getting any errors
Part of what was confusing me is that the variable angle in your code is not actually describing an angle. It's a ratio that is limited to the range [-1..1]. Then you take the arcsin of that ratio to get an angle. This doesn't affect the code at all, but it was confusing.
actually yeah, i am getting an error sometimes, and sorry about that
Hi! I have a script and I dont know how to do that idea.
Now if I exit the vehicle (the vehicle is on the side) the camera rotates to the rotation that the vehicle has.
So the idea is, if I press "e" (exit the vehicle) the camera rotation is resets.
// using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityStandardAssets.Vehicles.Car;
public class carManager : MonoBehaviour {
public Camera carCam;
public CarUserControl userCtrl;
private bool inVeh;
private GameObject player;
void Start()
{
userCtrl.enabled = false;
carCam.enabled = false;
inVeh = false;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
if (inVeh == true)
{
vehicleControl(null);
}
}
}
public void vehicleControl(GameObject playerObj)
{
if (inVeh == false)
{
player = playerObj;
carCam.enabled = true;
userCtrl.enabled = true;
player.SetActive(false);
player.transform.parent = this.transform;
StartCoroutine(Time(true));
}
else
{
player.SetActive(true);
carCam.enabled = false;
userCtrl.enabled = false;
player.transform.parent = null;
player = null;
StartCoroutine(Time(false));
}
}
private IEnumerator Time(bool inVehicle)
{
yield return new WaitForSeconds(1);
inVeh = inVehicle;
}
Maybe:
float AngleOfReach(float dist, float grav, float vel) {
float ratio = (grav*dist)/(vel*vel);
if (ratio < -1 || ratio > 1) return float.NaN;
// Not sure about whether that's the right way to write NaN
float angleSteep = Mathf.Acos(ratio) * 0.5f;
return angleSteep;
}
(I think you were multiplying by 2 rather than dividing on line 55.)
(Sorry, I need to run. I hope it helped.)
will try it, thanks!
also i am multiplying by 2 instead of dividing because the angle was too low
I just went from the equation you posted.
gotcha
there's a lot going on in your project
there really is
what is your gameplay objective?
RTS game with lots of explosions
so why do you need this value
are you trying to model an artillery unit with unity physics?
something like that, yeah
is it important that the shell be a Rigidbody
or is it like most RTSes
where there isn't really physics gameplay
i would really like it to be a rigidbody
okay
do you want an #archived-code-advanced solution?
or a #๐ปโcode-beginner solution
honestly something that just works
been trying to do this for like a week
because you'd just transform . position = ... and do a parabola with a kinematic rigidbody
you would do a constant xz change and the parabola for the y
Is probably best a question that should have been asked in #๐ปโcode-beginner
i will get slapped for crossposting
Should have started there.
true, true
it's okay
i don't think computing an angle makes any sense here
you can look at every artillery unit in every RTS game that anyone's ever played, and you won't find that calculation in it
why is it important it's a rigidbody?
if the answer is "novel gameplay" that's great
how do they do it in those games then? Is it like you described?
but if it's not... if it's because you just want collisions it's bad
:(
You can raycast where something will travel in the current frame without all this stuff.
if that raycast hits anything you can say it will explode there.
honestly with the amount of trouble im having i think i will have to do that
You should have a start Vector3 and a end Vector3 IMO
๐
Shells don't magically update mid flight to always hit the target. It's a fire and forget kind of mechanic usually.
i am aware :D
If you have a start and an end like where you clicked you can more easily make an approximation that looks right.
oh i can imagine
but ill have to return to this problem when i decide to do missiles
You know it is going up until the halfway mark
that is true
then it is going down
All you need is the vertical component where it maxes out.
Then you know the midpoint
and the height
Or you can just wait until it has moved past the X/Z midpoint between start and end
Hi. I'm making origin shift scrip, and I get huge performance spike from physics engine when the origin is shifted. Is there a way to fix it? And thats what profiler shows "Physics.SyncColliderTransform" ~ 30ms and "Physics.FetchResults" ~ 14ms.
disable syncTransforms while your operation is running, then re-enable when it's done
should be Physics.autoSyncTransforms or smth
Should look sth like this?
if(isCameraFarEnough)
{
Physics.autoSyncTransforms = false;
//Doing origin shifting here
Physics.autoSyncTransforms = true;
}```
yup!
unfortunately its not working ;_;
is it 2D maybe?
3d
hm
can you give an example of what your origin shifting does?
(like, code operations steps, assuming you can't share code)
if it's for multiple objects, enable/disable transform sync before and all objects have performed the operation
Im moving sth like root gameobject
private void Update()
{
if(new Vector2(cam.position.x, cam.position.z).sqrMagnitude > changeDist * changeDist)
{
Physics.autoSyncTransforms = false;
ShiftAmount -= new Vector3(cam.position.x, 0, cam.position.z);
Vector3 deltaShift = - new Vector3(cam.position.x, 0, cam.position.z);
//cam.transform.position -= ShiftAmount;
transform.position = ShiftAmount;
onRootChange?.Invoke(ShiftAmount,deltaShift);
Physics.autoSyncTransforms = true;
}
}
``` sth like this
nothing fancy
yea that shouldn't cause any spikes normally, uh..
maybe if you disable RB/collider and re-enable after 1 frame, it could go away
would that work?
I think it's trying to resolve stuff for the position change, and struggling since it may meet different colliders along the way
idk, i think it will try recalculate colliders transforms after enabling colliders anyway, btw. I also have a lot of colliers ๐
it could be little below 10k
and also i have only colliders without rb so its shouldnt be a problem with "self collision"
Just FYI: I did a lot of testing and a lot of forced restarts of my machine. File.WriteAllBytes() was not the culprit. Somehow, calling Graphics.CopyTexture() on macOS causes Unity to hang and freeze the entire machine some time before the next Update() loop is called. I have no idea what is causing it, but it is new, and as far as I can tell, it's unrelated to the macOS file system security.
Thank you again for your help and advice.
is there any place i could realistically ask about the engine source code? not the c# reference, but the actual source code.
i'm specifically wondering about how s_instanceBehaviourManager works
@uneven sorrelWe would need to see the backend code that does that. Before unity I used to use Allegro.cc to do a lot of 2d side scroller games, but keep in mind is a C++ based deal with no where near as much built in functionality as unity has, but it gives you much more flexibility for copying images and the like. You might write a .dll that works on mac OS instead of hanging. It's probably some kind of unhandled NaN, null, or do...while
Hey guys, I just wanted to ask. I have read that the composition software design pattern is preferred over the inheritance approach. Is this true?
it depends heavily on the context
and even within composition over inheritance after the implementation of the composition architecture you can use inheritance (see MonoBehaviour)
preferred, yes, but unity is designed more for composition over inheritance, hence, its component structure on the game object . . .
though this does not mean inheritance is bad and can't be used . . .
its a general direction you want to lean into when designing foundation, but on a smaller scale, inheritance will win in usability
Yes. I'm sure you're right. Once I realized it wasn't the file system but something else, I was able to find an old forum post from 2015 that explored the same issue. It seems that it has something to do with macOS being behind in their implementation of OpenGL (or Metal), though it is strange that it worked perfectly fine exactly one year ago.
I re-implemented using GetPixels and SetPixels32, and it makes an image ofโฆwell, at this point somethingโฆwithout crashing. A little tweaking, and I should have it working tonight! Thank you again for the help.
https://forum.unity.com/threads/solved-custom-shader-bug-on-macos-high-sierra.636955/
I wanted to ask because im practicing writing more modular code
so in terms of modularity, composition gives that more in unity because of how unity is designed right?
Thanks, ill check this out
Selling the idea to management is also a difficult. You need to be able to explain in plain words exactly how this is going to help get the game done faster. Something along the lines of: "Whenever we add new stuff to the game now, it takes a long time to do, and there are lots of bugs. If we do this new component object thing, it will let us add new stuff a lot quicker, and have fewer bugs."
Bad coda many bug, bug bad, money lost.
And you can avoid that by making code more modular right?
and easier to debug
to an extent
it's easier to design your components (scripts), as in, a stacking manner to add/remove functionality, but it is harder to reference properly without relying on dependency . . .
but isnt the point of making code modular to not have scripts depend on each other?
bugs can become less obvious, since now you are encountering issues with interactions between independent components, that can only manifest in specific scenarios, you get problems with initialization, lifecycle, design time errors etc etc
yes, you just have to set up how your components "talk" to each other and pass information to avoid it . . .
so things like unityevents and singletons
but i did hear singletons are not very good to use too
singletons are fine. the problem is how (new) people over/misuse them . . .
there is no way to establish a completely decoupled system, there is always a coupling point, it can be masked, singular, be some di framework, event bus, ecs system, but its there and it will require a certain composition so that the entities behave as you intend
yeah, if you are using it for an object and thats the only object you are going to have in your project then its fine right
or just only one class and thats it
What I'd note is that overuse of inheritance hurts, fast. If you work things around inheritance you'll quickly find you need to fight it to get something done, and then things can get really ugly. Learning the limits of these things takes practice sadly
so what your saying is there has to be some level of dependencies between gameobjects?
true, you can only go so far with a completely closed-off, independent system. at some point, your game will differ from others with how you communicate and apply the coupling (injection) in a safe way to avoid issues . . .
this cannot be more true. i always tackle this when thinking about an item database. i've done a simple inheritance structure, but really want to test a compositional approach . . .
what im saying that if something has a meaning, that meaning has to be described. I.e. a projectile may ignore the fact it doesnt have a mesh renderer code wise, but it wont ignore the fact that it lacks a collider, it wont error out, but it will lose its meaning as a projectile. and then you would have to ensure it has a collider. you can delegate that to the designers, relying on them to establish those components for each and every projectile, but then you get another set of even nastier bugs related to human error during data setup.
and that in ideal scenario where runtime changes to the components are not required
I think there is something called requiredcomponent method that checks to see if the gameobject has the required component right?
that simply enforces the existence of the component, but yes
oh i think i see what your saying
if the gameobject doesnt have the component and it errors out then the designers can get confused as to whats wrong right
because they might not have the knowledge of checking the console logs
example, designer adds a collider, all good. He made 20 projectiles, all good. Starts game all good. Later you discover that some colliders are misaligned, wrong layer set, mesh missing etc, and that is not obvious on playtesting at first.
nothing throws errors, it just doesnt work as intended
and since nothing throws errors, you are not sure what to debug
so you have to add debug logs and asserts right
its a simple scenario where you can quickly figure out what is wrong, but there are ridiculous cases of that
right
i had bugs for ui where designers heavily relied on UnityEvents, debugging that is a nightmare
but im derailing, its not why i said it initially
edge cases can be ridiculous and found anywhere. i just found one while writing documentation to explain the use of a class' methods . . .
do you also do unit testing?
i think thats also a way to test edge cases
yeah, i do for this. i did not think about this case bcuz it was recently added . . .
i just have a question, i dont have much experience with unit testing so i wanted to ask what you would usually do unit testing for?
i use it to check that each implementation created works as intended . . .
my timer class, e.g., i run a test to ensure it's paused when i suspend the timer, it's running when i resume, it's cancelled when i cancel it, and it's complete when the duration expires . . .
yes, these are runtime tests . . .
i haven't, but mainly for checking your editor extensions since it has access to your editor code . . .
Makes sense
One more question
about writing documentation
is it about writing how and why you coded a specific project?
documentation provides (detailed) information on the class and its public members . . .
like commenting your code?
you describe what a class does
you describe what an event sends (its action)
you describe what a field represents
you describe what a property returns
you describe what a methods does . . .
i'm creating this as if an asset. so i'm doc'ing all the available members. finishing up the readme rn . . .
learning (to actively use) git, writing docs, and creating packages for modular use . . .
good effort, still painful to have to write comments in that style
visual studio just autocompletes them for you
"do not put the cat into the microwave"
what
idk is this advanced or not, regardless, what's a fast way of knowing if a point X is inside a direction d within a certain angle a, being d the center of that angle, kinda like an FOV situation, here's an image
i thought of checking if the dot products with the sides of the angle are positive but isn't it too much calculation? i'm not familiar enough with unity's tools for this kind of stuff
it's 2d btw
yes dot is faster by a huge margin, you can convert it to angle https://gamedev.stackexchange.com/questions/69475/how-do-i-use-the-dot-product-to-get-an-angle-between-two-vectors
yes, you can use dot product . . .
also if dot < 0, return
@smoky rose however i can see that getting an angle out of dot requires normalization (if i read correctly) which makes it on par with Angle()
actually
that is exactly what Angle() does
public static float Angle(Vector2 from, Vector2 to)
{
float num = Mathf.Sqrt(from.sqrMagnitude * to.sqrMagnitude);
float result;
if (num < 1E-15f)
{
result = 0f;
}
else
{
float f = Mathf.Clamp(Vector2.Dot(from, to) / num, -1f, 1f);
result = Mathf.Acos(f) * 57.29578f;
}
return result;
}
true, i just looked at my code and i use Angle to check if it's within a fov . . .
i'll try with dot and/or angle but i'm thinking that I may have a problem if the angle is bigger than 90
i also use Vector2.Dot to check if the target is in front or behind first . . .
I want to make the walls that would not be visible from the characters perspective hidden, how would i do that?
I've tried googling it, but cant seem to get results which match what I am asking
you need to check all tiles against the two side-planes of the characters view frustrum and cull them if they are outside (i.e. turn their renderer off or overlay them with "fog"). you do that by finding the two direction vectors that are normals of those planes (i.e. directions orthogonal to them), conststruct a plane from them and do a side-check. if any one side-check fails, the tile is outside the frustrum.
Hey guys, trying to compile a DLL in Monodevelop but I get these errors when I use (nameof) and also when i use Lambda expressions
Any idea whay?
I am using these references:
Maybe you're not using a compiler that supports c#6 https://stackoverflow.com/questions/32943593/the-name-nameof-does-not-exist-in-the-current-context
Well if they're using mono develop, that's no surprise
I suspected that too
I am also getting these problems here
It's been deprecated and not suggest for use for 8 years?
MonoDevelop uses unitys Mono-Bleeding-Edge dll which unity uses however VS uses Microsoft Dlls
The Microsoft DLLs, can cause incompatibility problems in some platforms such as (MacOS & Linux). Even if the asset is intended for Editor only use
Pretty sure that would only happen if you misconfigure your IDE and use unsupported features
Yeah those are issues related to an insanely old compiler/C# version
the nameof thing you can only really fix but inputting it as an actual string (very bad), the default issue you fix by giving it the type it should default (default(Color))
Thanks guys, I will do more research
oo let e try this
I wouldn't use default for this though, because I expect the default for Color to be 0, 0, 0, or black
default (without the braces) is not supported in his version either
So if you give it the actual color 0, 0, 0, it won't know if it's that or default
I already said to use default(Color) instead?