#archived-code-advanced
1 messages Β· Page 17 of 1
yes, out of the page
one of the problems is that when i set the drawings to local space, they appear basically somewhere else entirely
i don't know whether your page is facing 0,0,1 or 0,1,0 or..
i think you gotta take a big breather
and reason about this in your head first
Ok I'll ask again then
the page only has one rotation, and its -39 degrees on the x axis
you can try googling "unity draw github" and also see some results
Does anyone have any documentation on what batchmode does exactly, and specifically how it should affect rendering except for not calling Camera.Render() ?
i think you can also contact unity support and maybe they can give you a more detailed explanation
Oh right thank you
I'll do that
what i was typing was basically saying that i almost have it working, the positions and rotations match the paper the first time https://i.imgur.com/mxNpZiD.png, https://i.imgur.com/fLQLP9o.png
for some reason, the second time you rotate your canvas, this happens https://i.imgur.com/EOZOon4.png
okay i see where the misunderstanding could come in
i mean, surely the line renderer is parented to the paper?
so when i turn my camera, the canvas turns with me
i asked you if it's supposed to be naturalistic
the line renderer is parented to the paper
is it?
the paper is parented to an empty which tracks the camera rotation
is the goal to have everything behave naturalistically?
yes, the first two screenshots are more or less how i want it to act, with the exception of the ends of the lines connecting to the center of the canvas for some reason
did you try googling the thing
i suggested
it looks like there are a lot of bugs in your code
most likely lol
i think the hard part is translating the behavior into code
there are a few bugs ive fixed between my posting of the code and now, evidenced by how the canvas now rotates the first time at least
but yeah
a lot of it is really messed up
so
i mean this is for a game jam
you can use the github repos that try to solve this
there are many ways to draw
i was kind of hoping that someone would provide me a solution to rotate an array of points around another point in space so i could just scrap what i had and use their solution
the solution you are asking for is reinventing local space
which if you have all these bugs
why try to reinvent the idea of local versus world space
you're not going to do that correctly, as you can see
i suppose so
so...
you have to use local space
you are actually really close
your raycasts are wrong
you should just try to fiddle with things in play mode
sure
so right now i get the position of the line by raycasting onto the page, then basically lifting the line off the page by moving it in the opposite direction of the raycast direction (so the line doesnt clip into the paper)
but this hit.point is a global position
when i set the line renderer to local space, it makes the lines appear like, 50 miles away from the canvas
do you think that the fact that hit.point is a global position, combined with the local space setting is causing this?
and if so how would i take the hit.point and convert it to local space
why are you offsetting the point by half a meter
let me show you instead of explaining
well yes of course
because it's not transformed to local space
i've been saying what to do
anyway i think you'll figure it out π
https://i.imgur.com/FUld55p.png lines clip into paper if i dont offset it
would i use transform.inversetransformpoint to turn the hit.point into local space?
yes
okay i gotta go
What's your goal? To ensure you don't forget a particle component on a GO with a script that depends on it? If so, I tend to just add my Assert.IsNotNull() directly in the script itself (since they're compiled out for production builds) - I find out right away if I forget a component or whatever
@regal olive
public class MissionIcon : BetterMonoBehaviour
{
[SerializeField] private TextMeshProUGUI StatusText;
private void LocalAssert()
{
Assert.IsNotNull(StatusText);
}
private void Awake()
{
LocalAssert();
}
}
that's my standard pattern
If you wanna spend whole day making tests for cosmetic stuff sure π€
does anyone know how to add camera shake if a player is running?
Kinda feels like one of those tests you write to verify requirements instead of behavior. Having a particle system with spheres is probably not sufficient to prove it's what you need.
By rotating it if the player is running
i also use the asserts occasionally for library code
as my super discount documentation
we don't have infinite time on this earth to write all the instructions
then again anything i share as source people can always modify if GetComponent based workflows are inadequate
so it's worth just doing everything as easily nice friendly base case as possible and owrry about power users later
I thought I would try to export my docs from my shared library DLL .. oof.
1500+ errors
(since i have warnings as errors in my codebase)
solution:
π
is it possible to have a custom package has a dependency on a another custom package? because i'm getting errors.
No unless you use scoped registry like OpenUPM
fix plz
How can I write my own built in function that has a specific execution time? Specifically, I want to make my own globally accessible (identified by monobehavior) method called LateStart(); that fires off after Start()
Is that something pretty simple to do?
There is section called Script Execution Order in Project settings
You can make specific script execute faster/later than others
You could expose event from that script for other scripts to subscribe
Awesome, thanks!
@jolly token is open-upm widely used?
Yes
I'm trying to download files through .NET's class Webclient and have a callback when the file is downloaded. I cannot for the life of me figure out why I cannot subscribe to the DownloadFileComplete event though.
https://learn.microsoft.com/en-us/dotnet/api/system.net.webclient?view=net-6.0
anyone that has a better idea than me?
Your method needs parameters which match the delegate
does anyone know why my database initialization doesnt work ?
it's a brand new project with an empty scene that has an object containing the script above
Probably beacuse it's async and it's not done connecting
Async operation
You're checking for fb_db immediatley after calling Check_Dependencies
Which is synchronous but FireBaseApp.CheckAndFixDependenciesAsync is not
If this method is only done once, consider making a component that initializes it for you when the application starts
Then add a method to it that accepts an Action that can be called when you actually initialized the database
Because you never know when it is
So you store those Actions in a list in the monobehaviour and have an Update method inside of it invoke them all as soon as the database exists
Just remember all those calls will be asynchronous as well, because they are in databases
So the tas that represents this operation will have to be stored aswell
Welcome to Asynchronous programming in Unity
Unity avoided asynchronous programming and now it will bite you in the ass
Creating a general system that can store all of this for you is probably the best answer. You will store all delegates in it and whatever should happen with the result. It's basically the old callback hell that you used to have before async-await programming, but now you manage it yourself
But you can also try it all with ContinueWith(). Just remember that the moment you call _task_.Result, the result might also throw an exception
Hello! I have a backend system to make it work in Unity. But do not want to cal APIs directly. I'm thinking to code a library sitting in the between Unity and Backend.
In order not to suffer from versioning in the future, I need to make a very wise abstraction, for sure.
Do you have any suggestion before I start? Thank you
So from user login to all CRUD operations will be handled by this Library with Unity objects.
in the meantime, however, the API v2.0 will come and I do not want to break my previous applications using the version Library 1.0
.NET's class Webclient
useUnityWebRequest
@mint sleet it sounds like you need to separate any calls into your dB into a separate datalayer class or project. Then you can code a data adapter between your client calls and the data layer, which would abstract the calls and help wit versioning
@balmy cargo if your async method needs to finish you can call GetAwaiter().GetResult()
I use that often in business applications where we have async and sync colliding
are you saying you authored a REST API method POST /login that takes a JSON object of the form {"username": "some username", "password": "somepassword"} ?
do not do that
It's literally the MSDN recommendation
it is bad advice
Why
it isn't the right way to interact with unity or the firebase unity api
the original user is gone anyway, but i think @balmy cargo will quickly start to comprehend what is going on
without anything too complicated
@balmy cargo doesn't know what the Async means and provided he googles that, he'll be fine
You can't await in synchronous context. He needs to either get awaiter or use async code. You haven't explained why you shot down my answer at all
Hey guys, I have a question about detecting "bunched up" gameobjects.
Let's say I have a map of a few mobs in it, and I want to cast a AOE spell onto the area with the most bunched off mobs
How do I detect via where to place the spell?
i think as you become more experienced in using unity it will be easier to give good advice
I'm very experienced in untiy. You still habet provided an answer
I have map 1), and need to know where to cast spell such that I cast on map 2)
So you want most optimized place to use your spell
Yes, exactly, but detect it through code, not player controlled
You could do a KD tree and spit into certain size zones then count in zones
alright i'll look it up
thanks everyone
Or do n^2 comparisons and measure all distances
π³ A KD Tree, true
I haven't touched that stuff since Uni, but I feel like that's its purpose
Having an ai always have the right answer could be very difficult
Maybe try randomly selecting 10 units and then see which has the most neighbor's?
You could find a local maximum but not be the most efficient
For most simplest and basic way, I could just divide the map into 4x4 cubes, and run overlap sphere on it, and see which one resulted in most mobs
obviously accuracy wise this isnt better than a KD tree but this is very cheap comp wise
Cheap and fast is good you can iterate on it later
this is a pretty hard problem
Aye it's traveling salesman just worded differently
consider that most of the time, the center of the optimal circle will not lie on a unit itself
Well, once you have a rough idea of the bunched up quadrant, then take all the mobs in it
then average out their pos
additionally, k-d trees don't really give you the right shape
it just involves many layers of steps
there is a datastructure for circular ranges
but i think that's pretty premature
consider what the problem would look like in 1D
Yeah honestly from game play perspective, randomly selecting a unit and then doing a spherecast for other units or something might be the best bet
But then you would always center on a unit
And you'd have to accept "good enough"
I think what you can do with KD tree is, find out the most populant quadrant,
then discard the KD tree, take the all the mobs in that quadrant, get the center mob, then now, scan all mobs near this mob within X distance, and get average of that to get ur circle's center
The goal of the attack is to hit a unit? Wouldn't you rather always be centered on one to increase those odds?
so even if the most "bunched up" mobs fall under 2 squares, and not just 1, then you can still cover both
hmm... think about what the problem would look like in 1D first
don't get anchored on this kd tree thing
it's a boss jumping up and smashing down at the most grouped up units, so if he misses any targets in the deadcenter, it makes sense
I definitely got some ideas here to expand on it, but Ill do the basic one first
1d? That's just a line. Do you mean 2d?
i think i figured it out by following my own advice
You could adapt dynamic programming
i wish you would try...
You could also try building some kind of heat map and jumping to the place with the highest "temperature"
it is a dynamic programming problem i don't think there is an improvement from doing it dynamically
this is close
you don't really care about the region with the most points you don't care about a rectangular area that has a lot of points
At least I'm giving ideas not riddles
a k-d tree doesn't help you
i think the other key insight here is that, why assume there is only one point that is the best location to cast
there will be a region of points
this is clear in 1D
in 1d you can draw lines of length Radius of Spell on each unit. the interval (the region between two points) with the most overlapping lines - any casting position in that interval will have the maximum number of units targeted
@limpid prairie in 2d you would draw circles on every unit, of radius spell effect. any point in the region in your image with the most overlapped circles would have the most units hit
@jolly token in 1d, the dynamic programming is easier to see - i think the reason it works is because as you query more points
the overlapping regions with the most number of points can only be the same length or narrower
i'm not really sure how to translate that into 2d though
it might not be true in 2d if you are querying point by point, there is something else you have to do
yeah i think you can do it point by point in 2d. you will want to preprocess the distance between every point - in this sense the data structure that supports circular range queries will help you. the range you are interested in is 2 * spell casting radius, because that will identify the (narrowing) region of best cast positions
i'm just not sure how you deal with the weird shapes you get when you overlap circles :/
anyway pretty good problem
okay i think it's
This kind of problem is NP-complete problem.
yeah
i think that makes sense
yeah
@limpid prairie you should use the greedy algorithm from that paper with number of disks = 1
if you have a lot of units you will have to use RKCP2 as specified
and it will be an approximation
but it wasn't tested with 1 disk
thanks for finding this @jolly token π
greedy is fine - it's O(n^2)
Yeah it is pretty interesting question
Oh damn wtf
But isn't that computation-heavy though?
Ofc that gives the best results
collision checking in Unity isn't the lightest, but I guess this spell isn't going to be cast often so it's totally feasible
Hello, I need help saving a list variable as a json file
and then decoding it back into that variable
Search up JsonUtility Unity
JsonUtility can't serialise a List<T> so you'll need to put the List into some wrapper class like
public class SaveBlah
{
public List<T> MyListOfThingsToSave;
}
As other channels are busy I'll pop this in here, is there a way to convert or pass in a System.Type variable in place of writing the actual class name?
I did something that works but.. might be godawful, lemme dig up the code
/// <summary>
/// If you can read and understand this method without semantic satiation on "type",
/// you win a prize: https://stackoverflow.com/questions/43080505/c-sharp-7-0-switch-on-system-type
/// </summary>
private Container GetContainerFromType(Type type) => type switch
{
Type _ when type == typeof(PlayerModel) => _cosmosPlayerContainer,
Type _ when type == typeof(SpaceGameSettings) => _cosmosSpaceGameSettingsContainer,
Type _ when type == typeof(UserMetricsModel) => _cosmosUserMetricsContainer,
_ => throw new NotImplementedException(),
};
comment included because it still makes me laugh
i read that article one day and after could not make my brain comprehend the word "type" any longer
lol
(obviously you don't have to switch/return something, but since you're in advanced I'm sure you can pick out the useful bits without help)
Thanks, I'll try and digest that :)
i think just do it the right way?
There is usually a non-generic version accepts Type parameter for those kind of method .. π€
pardon?
There is no AssetUtilities.LoadAsset(type) kinda thing?
public Object LoadAsset(string name, Type type);
this exists
you need a name/path though
Yeah for Unity APIs they have it, Idk what AssetUtilities is
AssetUtilities is mine
i can change the function on the other end
it basically returns a list of all assets of a type
Okay how does that one look like, you can have overload that accepts type parameter
you'd have to make the type an actual normal parameter
instead of a type paramater
List<UnityEngine.Object> LoadAssets(Type t) {
...
}```
Of course you will lose compile-time type checking here, which is expected since the type is now determined at runtime.
Yeah then use AssetDatabase.LoadAssetAtPath(string assetPath, Type type); version
Converting to your preferred type later
No errors, so I will test this rn, but is this how you guys meant? (thanks for the help by the way :D)
Yes
oki checkin now :)
@jolly token @sly grove Big thanks to you both, it works all good, I was driving myself insane over that as usual lol
you can still make it generic if you cast to T after loading
Hi im trying to read data from my mysql database, and it gives me an TlsException: Handshake failed - error code: UNITYTLS_INTERNAL_ERROR, verify result: 4294936704
code:
You might need to explicitly tell MySql to not use a certificate when connecting to the server. This is usually done in the connection string. You'll have to look at the docs to know how, though.
Fair word of warning though, I googled your error message, and told it to search for this error explicitly (no fuzzy searching), and I got 4 results, in which 3 of them were copies of the first one
so u r saying my only hope is just to find a programmer that knows how to fix this problem
Yeah
Looks like a Unity issue though, see if you can reproduce the error but outside of Unity, in a console application for example
You want me to create this issue again outside of unity?
Yep, so you determine whether the issue comes from Unity, or MySql
If you don't get the error with the exact same setup, then Unity is at fault
OK, also idk if I'm going overkill cuz I'll I need is couple of buttons and gui with mysql, do u recommend something less overkill?
Ok*
Like, you're making a SQL query runner or something?
It's something for school with a machine we built for producing energy, and every student has a score, so the data goes to mysql and the app just takes the data and displays a leaderboard
So no game at all, just GUI?
Ye that's why I'm saying I think I'm going overkill but idk any other engine
Yeah Unity isn't the thing you're looking for here, if you wish to keep C# you can make GUI apps in C#
And now that I think about that, a website would be better cuz ios problems and stuff
Is it easier in Java script to work with mysql?
Depends on the framework that you use, but I'm sure most of them (like Node.js, React, etc.) have MySQL connectors
Alright, I appreciate the help π
DM me for MySql problems
hi, i have a question. I only want my touch control buttons to show when the game is running on mobile. The problem is that my game is built on webgl.
public class myClassA:MonoBehaviour
{
public myClassB;
async private void Start()
{
await myClassB.DoSomething();
//continue with other stuffs
}
}
public class myClassB : MonoBehaviour
{
async public Task DoSomething()
{
await Task.Run( () => {
//stuff
});
}
``` Im having a NullReferenceException and a TaskCanceledException
I did assigned myClassB through the inspector so myClassA has a reference, any ideas on how to solve this?
First things first, post the full errors, stack traces included
okey ```
NullReferenceException: Object reference not set to an instance of an object
Namespace.ClassName+<FunctionName>d__49.MoveNext () (at ScriptLocation:LineOfCode)
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.TaskAwaiter.GetResult () (at <695d1cc93cca45069c528c15c9fdd749>:0)
NameSpace.ScriptThatCalledTheFunction+<Start>d__11.MoveNext () (at ScriptLocation:LineOfCode)
--- End of stack trace from previous location where exception was thrown ---
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () (at <695d1cc93cca45069c528c15c9fdd749>:0)
System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_0 (System.Object state) (at <695d1cc93cca45069c528c15c9fdd749>:0)
UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <3be1a7ff939c43f181c0a10b5a0189ac>:0)
the other error TaskCanceledException: A task was canceled. System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.TaskAwaiter.GetResult () (at <695d1cc93cca45069c528c15c9fdd749>:0) Namespace.ClassName+<FunctionName>d__2.MoveNext () (at ScriptLocation:LineOfCode) --- End of stack trace from previous location where exception was thrown --- System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.TaskAwaiter.GetResult () (at <695d1cc93cca45069c528c15c9fdd749>:0) NameSpace.ScriptThatCalledTheFunction+<Awake>d__91.MoveNext () (at ScriptLocation:LineOfCode) --- End of stack trace from previous location where exception was thrown --- System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () (at <695d1cc93cca45069c528c15c9fdd749>:0) System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_0 (System.Object state) (at <695d1cc93cca45069c528c15c9fdd749>:0) UnityEngine.UnitySynchronizationContext+WorkRequest.Invoke () (at <3be1a7ff939c43f181c0a10b5a0189ac>:0) UnityEngine.UnitySynchronizationContext:ExecuteTasks()
what are you trying to do?
it's telling you what the error is
Namespace.ClassName+<FunctionName>d__49.MoveNext () (at ScriptLocation:LineOfCode)
That's not valid, please don't redact information from messages
Stack traces contain essential info, especially where in the code the exception was thrown
We need that info in order to debug
What I can say though is that both errors are related, the NRE forces the task to cancel at some point
yeah, its kind of hard when you have a NDA, anyways Im trying to await the response of a fetched data from a database, and according to whats in the data continue with the logic, the script that handles the fetch is separated from "myClassA" thats why I make a reference through the inspector.
async public Task DoSomething()
{
await Task.Run( () => {
//stuff
});
what is this actually doing?
lol
you should be using UniTask
are you trying to access a database with a blocking IO API?
and you are trying to "taskify" it?
Most database providers provide async calls
Check the documentation of yours
Without the essential info, can't help further
Hello. Maybe someone can help me read value of some UUID? I am using Bluetooth LE for iOS, tvOS and Android. My script
public void ReadBattery()
{
BluetoothLEHardwareInterface.ReadCharacteristic(_deviceAddress, ServiceUUID, ButtonUUID, (data, bytes) =>
{
Debug.Log("Read Succeeded " + bytes);
});
}
is this Java?
in respond i am getting "System.Byte[]".
C# Guid is the same as UUID
assuming your byte array is actually a 16 byte guid, you can use this constructor
i tried this one - var str = System.Text.Encoding.Default.GetString(result);
But looks like i am not getting value, but just uuid...
ok so it's encoded as a string
so then just pass that string to this:
https://learn.microsoft.com/en-us/dotnet/api/system.guid.-ctor?view=net-6.0#system-guid-ctor(system-string)
Its too hard for me, sorry π
And this is looks like work with UUID not of this value?
im looking at it, Im having a hard time to what to use, All I want is to wait for the response and then continue with the main thread
I don't understand your english here, sorry.
guessing the implementation of uuid is not the same as the guid
UUID and GUID are the same
that is very easy
okay i'll share you the snippet
in a sec
but you have to tell me what htis is actually for
fetch data from a db...
i mean what is the application / game
i'm sure you can say enough in broad strokes
this is just part of being an engineer
idk what to answer, like, what genre is it?
for example, "i am building a virtual test drive experience in Unity for an auto brand"
does that make sense?
or "i am making a first person shooter strongly influenced by CS:GO" <-- valorant
why would you want to know that?
it's just table stakes for getting help for free
then it isnt free at all
i'm saying part of what you can learn today
is how to describe what you are doing
and understand that it doesn't violate any NDAs
i.e. "Not Doing Anythings"
it's too bad because
the solution to your problem is 3 lines
x for doubt it? lol
alright well so it goes
consider that there are certain things that i categorically do not want to help, as i am entitled to!
everyone has a line
i want to help people make games
you're talking about accessing databases
from inside unity
and i'm not the only person who told you that the amount of obscurity you are operating in is so annoying
two other people who have tried to help you ran into basic issues understanding what it is you are trying to do
{
public myClassB;
async private void Start()
{
await myClassB.DoSomething();
//continue with other stuffs
}
}
public class myClassB : MonoBehaviour
{
async public UniTask DoSomething()
{
await UniTask.Run( () => {
//stuff
});
}``` Im getting a new error, not all path return cant recall what
π who knows really
@jolly token c'mon "NDA" = "Not Doing Anything" is pretty good
Honestly, didn't notice it was pun π
lol
thing is that code makes little sense, how are you expecting the new task to run
i think the user is trying to access a database with a blocking API
but that's just my guess
Tasks and async and await, does not make things concurrent its just tools for working with concurrent stuff and repersenting futures
i'm not trying to be a blowhard, it just would really make my life easier to know some basic facts about what is going on
like if its truly a blocking database call, and you need it not to be. well you would need to setup your on thread to run the work on providing its thread safe
then you can use the Tasks to represent work happening on that thread
I was just going to say "doc is being a Google that collects analystics data for their service"
lol
now it is not too hard to setup your own TaskFactory and TaskScheduler that runs work on its own Thread providing all calls in it are threadsafe
well i wanted to share
UniTask.Void(async () => {
await UniTask.SwitchToThreadPool();
var data = BlockingIO();
await UniTask.SwitchToMainThread();
textLabel.text = $"Retrieved {data.id}";
});
as an example of how elegant the API is
never used that lib, just was talking about standard library ways to do it
though looks pretty smooth for one offs
though think i would toss the BlockingIO call in a try/finally, that way 1 exception does not prevent it from switching back to the MainThread
it won't get into a stuck state AFAIK
it will be peaceful
in the context of a specific RPG? what are you authoring?
a conventional baulder's gate style RPG?
when you say "level changes" what do you mean?
hmm okay
are you asking how to express waiting for a long time, in code for example, so that it looks like the quest text?
this is a good thing to want
so if your quest sounds like
Find the Dragon and slay it.
Return its tongue to the Mayor.
you want code that looks like the english words? because quests are already algorithmic / procedural?
you're saying "level changes"... i think that's sort of a whatever concern
do you just replace the scene based
replace aScene? or a scene?
what do you mean
focus on what i'm asking for a sec
do you mean replace the scene as in loading a new unity scene? or do you mean metaphorically replace the scene?
it's just important to use the right words you know, when you ask these questions
and people who ask questions on the unity code channels... they have different experience levels and say the wrong words sometimes, is all
it sounds like you mean an actual unity scene
Currently I'm trying to use visualscripting for making a graph
this is probably a bad idea too
so is using conditions, and all this stuff in the inspector
i don't think you should use Scenes, but that's a different story
i'm trying to help you see things in a clear way, which is that there's this long running Task - c# doesn't have such a thing really
where you are awaiting things to happen
because that's what the quest text looks like
?
hmm it's too bad this was an interesting question. i think you can use a long running Task
i think the core issue is that you don't see things like the quest text as procedural/algorithmic
you didn't know that's what it was
Is this dialogue tree type thing
dialogue trees kind of suck
What part are you having problem with?
Making the system? Managing the data? Populating event?
like people who write well don't use dialogue trees
they prefer Ink
something that looks like screenplays
and then, if you know how ink really works internally, it's a great insight into how to make quests - really, Long Running Tasks - generally
Gen Z is coming
lol
They don't know what ink is
ink's engine is, a Task that replays up to where you left off
what people want is Serializable Task
I want that
Ah ink is script language π€ https://www.inklestudios.com/ink/ interesting
ah have done similar things, where i have game actions and stuff tied into the loc files, so stuff can trigger in certain dialog
so for example
Find the Dragon and slay it.
Return its tongue to the Mayor.
async UniTask DragonQuest() {
var dragon = FindNpc("The Dragon");
await dragon.DiesAsync();
var player = GetPlayer();
await player.inventory.OnItemOwnedOrAddedAsAsync(FindInventoryItem("Dragon's Tongue"));
var mayor = FindNpc("The Mayor");
await mayor.inventory.OnItemOwnedOrAddedAsAsync(FindInventoryItem("Dragon's Tongue"));
player = GetPlayer();
player.gold += 100;
player.xp += 1000;
}
Generally I put them in the spreadsheet with conditions that can happen and actions to do π
it very heavily depends on the game and its setup
if you look at the internal scripting system for RPGs, they tend to look like what i wrote there
with the idea being that you can remember where you were along the way of that Task
the state of that Task gets serialized
last time i had to do it, steps of a quest where setup using a Command pattern
it is hard to do that generally, but not troublesome to do it within the limitations of a game
so it was easy to save state changes from each one taking place
and revert any if needed
@jolly token i believe the simplest way to do it is to store a "save point" integer that increments for every side-effectful method call, like player.gold += 100
the actually tracking part is just a statemachine per quest
i think all these systems eventually reinvent serializable tasks
in some way
you can do it informally or formally
Then I guess the await part would be pseudo?
not sure... i think you would just wrap it in a decorator
I'm interested now too, I don't mean to disrupt the answering, but with this setup surely as soon as the device is shut down or perhaps the program crashes, you lose any progress made upon that quest, because it's awaiting a async call, not checking conditions when one condition is updated?
really feel trying to shove await syntax into this problem just makes it harder to follow and debug
nah i mean, c'mon look at my snippet, it looks like the english language description of the quest
and absolutely none of this other shit does
anyway i am just trying to do, the formal version of what really big RPGs do
they have a scripting language that is the same energy
you are showing a best case, i am referring to it all, how does it work with our savefiles, how does it reapply its state to the world on load, does it allow undo etc
Hmmm Yeah this could be somewhat generic
Just restoring state part is not easy and can be messy
I guess it's like DB migration in a term
why i like the idea of things effecting state that needs to be restored using command pattern
How would i load a c# dll at runtime (il2ccp game)
AOT and dynamic DLL loading is conflicting by definition.
You'll need to use script language like lua or python or something
yeah a few approaches
class Quests : MonoBehaviour {
void Start() {
// slay the dragon
GameController.instance.data.AddQuest(async context => {
// method sets context.Quest variable and other things
await UniTask.WhenAll(context.player.level.Where(lvl => lvl >= 8).First(),
context.player.visitedRealms.Any(realm => realm == "Dragon's Realm"));
// mix animations, rules, dialogue. all in one place
// why not!
await context.StartQuest();
var dragon = context.FindNpc("The Dragon");
if (!dragon) {
context.EndQuest();
await UIController.instance.ShowToast("The dragon has already died")
return;
}
await dragon.Killed().FirstOrDefault(evt => evt.Killer == context.player));
await context.Effect(async () => {
// do some animations ghost animation
await dragon.transform.DOMove(new Vector3(...));
// give the player gold
context.player.gold += 1000;
// do an analytics event
GoogleAnalyticsV4.Event({,,,});
});
});
}
}
class Quests : MonoBehaviour {
void Start() {
// slay the dragon
// reactive
var dragon = context.FindNpc("The Dragon");
var dragonDied = dragon.Hp.Select(hp > 0).Pairwise().Select(pair => !pair.CurrentValue && pair.PreviousValue);
var dragonKilledByPlayer = context.player.Kills.Where(k => k == dragon);
var playerLevel = context.player.level.Where(lvl => lvl >= 8);
Observable.CombineLatest(dragon, dragonDied, dragonKilledByPlayer, playerLevel)
.Select((a,b,c,d) => a && b && c && d)
.Where(shouldFire => shouldFire)
// extension method that doesn't take if you've already taken this once
// during htis playthrough
.TakeOnceInPlaythrough("slay the dragon quest")
.Subscribe(async _ => {
await dragon.transform.DOMove(new Vector3(...), cancellationToken:token);
context.player.gold += 1000;
})
.AddTo(this);
}
}
}
@jolly token lots of ways to skin this cat
in the first example you'd need to use methods on the context or a custom async executor to increment the "step counter" of the serializer for the task
the positive is that it is really easy to read and debug
in the second example you don't need to do that, it can be stateless, but it is way more complicated
just like react it would rerun the quest every time anything in it changes
and that is also hard to implement
the second one might as well just be a subscription to a reactive thing
like rxjs wasn't in React's vocabulary
i might as well have just done an observable
it isn't doing anyhting for me to do it the react way
it would make things harder
Let's make it modular and decoupled and serializable π
Rx is neat for UI but I feel like it's becoming Perl
"Write once, read never"
lol
yeah i fixed the example
it wouldn't be that hard for multiple step things in observables
it would be "ContinueWithPlaythroughSavePoint("you found the dragon")"
if that makes sense
or really
Observable.TakeMemoized(..., "a name for this checkpoint")
what do you think
i think the first one is more powerful
but really hard to implement
Thing is when a designer implement this
They have to understand where to save and what to consider
And I don't trust designers
that would only be possible in the first case
the designer isn't going to come up with an animation
someone else will do that
That too π
i personally like to be able to author Timeline content in code
so that's why i think it's important to have #1, it makes it easier to add in animations, dialogue, UI effects, etc.
and just messing with game objects
these are the two approaches that can make these things very robust / low bugs
but only the first approach really looks like the text of the quest
And that's a good thing yeah
no i never write tests for unity
someone i'm sure has tried to do serializable tasks
in java i used a serializable fibers library but never serialized anything
wasn't necessary
i think akka can also serialize actors
very Erlang
it is nice to be able to just declare a variable, side effects be damned
if you wrap side effects in context.Effect(() => {}) you can do it
Hmm only if we can just jump in to middle of Task
it's like writing haskell
yeah in the java library it was smart
it kept a program counter
and leapt through the block points
Maybe possible in world of pure function
so if you deserialize a fiber, it (1) restored all the scoped variables and (2) skipped all the code up to the save point
Isn't versioning gonna be very challenging for that?
Like how do you even modify code with it π€
it's only possible to restore a previous version if the variables (local, closure) stay the same
but that's true in the RPG script code too
i wonder how those RPGs migrate for patches
probably jsut declares a "migrate" method
I wonder if that is possible in C#
someone i'm sure has done it
the cheapo way is to rerun the function, and just don't run the stuff in context.Effect
that's the Lispy way to do it
tHaT's NoT pReTtY
very cheap
yeah i know
but in my example it would work
and you wouldn't need a degree in CSharpology to pull it off
you would just hijack await
which you can do
...
Task Effect(string name, Action<T> action) {
// internal
Context.current.SetEffect(UniTask.Run(() => {
if (Context.current.HasExecuted(name)) { return; }
await action();
Context.current.SetExecuted(name);
}));
}
there is a C# api that looks like this
^ something like that. SetExecuted would write to your save file
could be even simpler
skip the action if the save file shows it was executed
whaddya think?
this is if you're rerunning the whole function
in a language that cannot guarantee purity
= bugs
i would rather allow it to be impure but use a custom async executor
The things that really irritating would be exception handling
In general term lol
For example you give user a 500 diamond for initial draw
And you do the draw, but the game crashed
Hmm no you send server call and game crashed
Now the diamond is gone and your Task is deadlocked
yeah
server call would be impure
i am not familiar enough with haskell
to say how it Deals
but there's an approach
Monad?
lol
that is essential
when i think language features, i think, shit we need an operator
Like when C++ developer became so excited and made std::cout
That's probably why C# banned overloading >> without int param
beginning with C# 11, the type of the right-hand operand of an overloaded shift operator can be any.
OH shit dream comes true
lol
Something is seriously wrong with my while loop. You can see the array has a length of 14 and it's supposed to destroy 2 objects and have a length of 12 by the end. But while it's reduced by two, the loop only runs once and only one of the objects is destroyed.
https://cdn.discordapp.com/attachments/377316629220032523/1021997202899480627/unknown.png
https://cdn.discordapp.com/attachments/377316629220032523/1021997203260178502/unknown.png
The only explanation I can think of is that one of these functions is somehow also removing an entry from the array, so it runs twice in one loop while only destroying one object.
Does your object remove itself from list on OnDestroy or something
@jolly token the object is a Toggle (as in the regular UI component)
it says there
hang on I oughta double check
hang on it might be a ToggleGroup thing
Does by chance the second object have the same name as the first und you have collapse on in the console?
nope definitely not collapsed. I ended up fixing the problem (even if I didn't figure out the specifics of what was causing the bug in the first place), by declaring the list object and removing it before destroying it
some editor flexible enough to copy-paste (not exactly, will always need small edits but) it into different projects and easy enough to use by dudes who cannot into programming.
Excel! π https://github.com/cathei/BakingSheet
Not that complex but what Clash royale does
https://github.com/smlbiobot/cr-csv/blob/master/assets/csv_logic/tutorials_home.csv
This also sounds like anti pattern my friend.
First, you are relying on static states (FindObjectsOfType*)
Second, it is still hard to refactor things and track references
Third, how would you handle dynamic object that instantiated?
I think he meant what he wrote- since it is suggested as replacement of singleton
really, its unity is just a pain in the ass with this, since you do not control object construction directly for most things
and do not have just 1 entry point
being too strict about any approach is just asking for headaches
That would be the root of the problem π
but i often end up with a service locator, that lets me request objects registered to it by type, and lets me easily swap those implementations out
in literally everything else i do that is not Unity, this problem is fully avoided, since i control object construction and what order things are constructed in, so pretty easy to do dependencies first, and pass them down as constructor args
use | like C++ streams
or rather ranges
I wonder, maybe service locator is better pattern for Unity as they aligns with GetComponent series π€
Itβs not the problem with using API. You are getting your states from static states without context, thatβs not flexible enough IMO
Iβd prefer generic solution like DI really. With this Iβll have to write lots of ad-hoc code to handle state and context properly.
I guess you can just go with ECS pattern if you prefer
di, referring to dependency injection?
yes
aka passing dependencies on intitialization
you'd make an interface for invoking that event and just initialize the thing doers with a reference to the implementation when you create them
how you're going to pass that reference is your choice
you can do every object individually in a test
passing in a mock
you can use a di container
you can access a static singleton instance
di is more dynamic in this sense
but if you have a framework than it would likely use reflection and bind it automatically from its container
I instantiate everything manually
zenject does reflection to bind the dependencies
you'd have an initialization method, and it would bind the objects according to some rules that you define
but you still have the choice to initialize any object manually
I just have an initialization routine where I initialize everything explicitly
If I needed dynamic objects that have dependencies, i'd create a factory, explicitly
Might be more code and somewhat clunky, but the good thing is that there's no magic involved
look at how zenject works, or check out di in aspnet core
essentially, its just an initialization method for you monobehaviours
and passing in the dependencies
How is it advocating singleton? Using singleton with DI is compeletely fine because the fact that it is singleton is hidden, you can always refator or swap the implementation
you are just being pandantic about it, its fine to have a few if they save you from other problems
Your example is also a singleton as only single instance would exist. The problem is not singleton, the problem is βsingleton patternβ
Btw my DI container impl does not use singleton anymore since I refactored it
think you are way more concerned with what you call "good code" then getting stuff done then
like having 1 object as a locator or a di container that is singleton is fine
more then fine, since it provides 1 entry point where dependencies for runtime or test can easily be setup
Hello everyone!
We are facing a rather odd issue, and we are unable to solve it so far.
Here is the situation:
We have a few packages imported into our game project, and one of them is
"collections"
2 of our components are relying on this package, but one of them is looking for 1.0.0, and the other one is looking for 1.2.0.
We don't have any problem until we try to build, no error msg nothing, but the build can not be done.
How can we segregate the 2 packages, or what other options we have?
We need both component to be working.
Thatβs fine, debating for better design is a good thing
private void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
reducedHP();
}
if (Input.GetKeyDown(KeyCode.E))
{
Noway();
}
}
public void reducedHP()
{
healthpoints--;
if (healthpoints < 3)
{
SecondPhaseStarts?.Invoke();
FirstBoss.SecondPhaseStarts = null;
}
}
void Noway()
{
healthpoints++;
if (healthpoints > 5)
{
FirstBoss.SecondPhaseStarts = null;
SecondPhaseStarts?.Invoke();
}
}```
On "SecondPhaseStarts.Invoke". basically when this object reach below 3 on its healthpoints, the other gameobject from another script that subscribe to this event has stop spawning. When it's more than 5 healthpoints, it respawns. It works!
BUT, when i made the healthpoints below 3 again, it still spawns and didnt stop. pls advice? π¦
hmm can you build an empty project?
it sounds like you have a complex project
2 of our components are relying on this package, but one of them is looking for 1.0.0, and the other one is looking for 1.2.0.
this doesn't really matter. they will just both use 1.2
it doesn't work like npm, this is a red herring
how do you know you aren't building? what is actually happening?
this isn't really #archived-code-advanced, try #π»βcode-beginner !
@undone coral
Thank you for the reply!
Yes indeed it's a complex project. Atm we trying to implement Singular (the analytic tool) and it causes this problem. Let me grab the msg we get during the build process.
(actually one of my co-worker making it, will ping you again in a bit)
can you build the project?
no. If the Singular package we have at hand is included, the build fails. (I'm still waiting for the report from my co-worker)
but if we don't have the Sing. in: we all good.
okay so...
i'm sort of stating the obvious here but why don't you contact them
nobody has any experience with installing this obscure thing delivered as a unitypackage
does anyone have an ide how to add a decent camera shake while running
google "how to add head bob unity"
bro you safed my life β€οΈ
We did. Not much progress so far (2 days...)
This is the package problem that I have mentioned
- What went wrong:
Execution failed for task ':launcher:checkReleaseDuplicateClasses'.
1 exception was raised by workers:
java.lang.RuntimeException: Duplicate class androidx.collection.ArrayMap found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-collection-1.2.0.jar (collection-1.2.0.jar)
Duplicate class androidx.collection.ArraySet found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-collection-1.2.0.jar (collection-1.2.0.jar)
Duplicate class androidx.collection.CircularArray found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-collection-1.2.0.jar (collection-1.2.0.jar)
Duplicate class androidx.collection.CircularIntArray found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-collection-1.2.0.jar (collection-1.2.0.jar)
Duplicate class androidx.collection.ContainerHelpers found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-collection-1.2.0.jar (collection-1.2.0.jar)
Duplicate class androidx.collection.LongSparseArray found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-collection-1.2.0.jar (collection-1.2.0.jar)
Duplicate class androidx.collection.LruCache found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-collection-1.2.0.jar (collection-1.2.0.jar)
Duplicate class androidx.collection.SimpleArrayMap found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-collection-1.2.0.jar (collection-1.2.0.jar)
Duplicate class androidx.collection.SparseArrayCompat found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-collection-1.2.0.jar (collection-1.2.0.jar)
--
I was wondering, maybe we could just segregate the 2 packages with namespaces maybe? Or any other way to do that? Because as far as I can see the problem here is the fact that we have 2 of the "kinda" same packages.
If I could separate singular's stuff, from the others... could that work?
okay
i mean you said collections package, i had no idea which package you meant, and here you clearly have an error message
and you're talking about an issue with the android build
it sounds very complex for you
you should wait for their response
Question: Is there any deterministic/decimal type that support big exponent value? Precision is not that important.
i.e. The deterministic version of https://github.com/Razenpok/BreakInfinity.cs
Bigint?
It'd be too big and slow. I don't need that much of precision, I want more of incremental-game kinda number
They are not deterministic since they are using double under the hood, thatβs why Iβm finding something else
Because I need deterministic calculation across platform?
Can you use two ints or longs. Basically scientific notation?
int baseValue;
int exponent;```
or maybe:
int hundredths;
int exponent;
Such that:
hundredths = 534;
exponent = 7;
Would indicate:
5.34 X 10^7
you'll have to write all your own arithmetic functions with this but it should work for what you need and be deterministic.
See if Decimal works for you. Itβs much less prone to rounding errors at the cost of a reduced value range and 16 byte size.
This is good, though Iβll need to implement some complex thing for multiplication etc. So I was finding if there is published solution first
Iβd love to use decimal, sadly I need less precision and more exponent
What exactly is your issue with a regular double?
best option if double doesnβt work is to just duplicate any other floating type implementation with a custom exponent size
I think floating point is the problem in the first place
because the math is not deterministic across hardware
it needs to be deterministic fixed-point arithmetic. Although the use case hasn't been shared actually...
All I have taken away from reading about that once is : just donβt even try
right - don't try to get deterministic floating point math. Do fixed point math instead!
Iβll just say that I need to run input synced simulation (e.g. lockstep) with incremental stat number π₯² I guess Iβll have to implement custom type
is Dear IMGUI used in the industry for unity?
pretty sure Unity's own IMGUI (legacy ui) library is basically a C# port of Dear IMGUI
that shit giving me nightmares
I was making a imgui console for development but i realized the package doesnt work good as i supposed, don't wanna code it unity's own either...
i would not say a port, but yeah its a IMGUI so heavily inspired by dear imgui
i really do not mind IMGUIs for tools
Which one do you choose?
Find the shortest path from a source point to several target points (specific type of a tile)
a--> (b1,...,bn)
Output: a--> bm
1- Dijkstra
2- A* for each target point
the 2 things are almost the same
just easier to influence A* into working in slightly different ways
A* is just Djiskstra with an extra heuristic function
also if 3d or working on the xz plane i would just let unity do it for you
I know what it is
its A* on a navmesh
I want to know which one is faster you guess
Run A* for each target point or Dijkstra
A* is faster if the hueristic is good
otherwise it's slower or equal to djikstra
A* with the right hueristic will check less nodes
Because that tile exists in many positions. So, there are many target points
this is irrelevant
both algorithms find the shortest path to all nodes or specific node depending on how you write/configure it
alot of the optimization for both of them will come down to proper data structures for the open and closed sets
and reducing the amount of nodes
I think classical A* works with one target point!
what are nodes in your case
Both algorithms work with one target point
grid tiles, a quad tree like thing or triangles?
Simple grid
I don't know what you mean
Dijkstra's algorithm (/ΛdaΙͺkstrΙz/ DYKE-strΙz) is an algorithm for finding the shortest paths between nodes in a graph
So, it does not have one target point
finding the shortest paths between nodes
It creates a matrix [v,v]
Hey so if I have a .asset file
how do I extract the mesh for it so I can modify it(change its index's from 16 bit to 32 bit) and save it back to the asset file?
it does have one target point
it's literally the same algorithm as A*
with one fewer function call
I've written it in college (10 years ago but still)
it builds a matrix for memoization purposes
If it finds the shortest path between all vertices, dude read
I have implemented it 15 years ago as well
Only if you run it from every node in the graph and don't stop it after finding the node you're interested in.
It is classical algorithm, right
see wiki
hmm strange
how the wiki is showing it being used to find the shortest path between two particular points
heuristic is just the hcost function added
I think you do not know the algorithm.
It should find the shortest path between all points because it uses the info
to go to the next
I know the algorithm. If you let it keep running it will find the paths to all points
if you stop it when it finds the point of interest
then you're fine
The difference with A* is you need to start with a goal node in miond in order to have a hueristic function oriented toward that goal
that's the only difference
yes, but A* classic heuristic is only for one target point
yes
it does not work with multiple at all
right
well acutlaly
it DOES
but
the hueristic just becomes useless
that's all
you can let it keep running after finding the target node, just fine
its also easy to just but it on a flag and disable that one added feature
yes, useless
I guess given what you're actually asking here
djikstra is most likely more efficient since a lot of work won't need to be repeated. But you could also just modify A* somewhat and have it re-use the costs calculated in previous runs just fine
modified A* would be fastest probably but simpler to just run djikstra until you see all your targets.
I am working on a similar project - tower defense game - where I precompute all the shortest paths up front
and have all the enemies just follow those precomputed paths
ultimately the performance ends up not mattering that much if you can precompute the paths and reuse them.
Which may or may not be applicable to your game
1- Choose n closest target points (n-nearest search)
2- Sort them by distance
2- Run A* for the closest one
3- After reaching, remove that target point and repeat
I think it is OK
Unfortunately, in my game, the roads are dynamic
in my game too
I do the pathfinding recomputation when the player changes the grid
but that happens in a separate phase from the enemies moving around
not sure how yours works
depending on the unit count and other factors, maybe want to look into more specialized approaches like what a rts game with high unit caps would do
At some point on the spectrum from "finding shortest path from a to b" to "finding shortest path from a, b, c, and d to e, f, g, and h" I went from using classical Djikstra/A* to more or less just using Breadth-First-Search and doing lots of memoization and it went better.
@timber flame you could also modify A* and/or Djikstra to pass in the heuristic and end condition as delegates, rather than having them hard coded as a target node + distance function to that node
not sure how bad that would be for performance, though
I have implemented flood fill/BFS
but now, we want weighting/priority
seen some approaches where instead of working the path backwards from destination like you do in A* or Dijkstra's, where it processes it all and saves directional vector information in each tile
this is literally what my current project does haha
i call them signposts
the AI just follows them
yeah supreme commander does a approach like this
like flow field pathfinding
Yes, creating them is heavy. Afterwards, it will be OK
Storing the direction
why i mentioned it depends on your unit cap
its way more expensive for only a handful of things following
yeah so you need to weigh your write/read ratio basically and decide if the cost to create them is worth it. In my game I have hundreds or thousands of enemies that all reuse the same paths so it's absolutely worth it
but if you are getting into hundreds of path followers
if your graph changes a lot, the cost to create them may be too high
also depends on whether your units are navigating to the same place or different places. If everyone is going to the same destination from different origins, flow field can be really efficient
really i just use pretty basic A*, but i made my data structures as effecient as possible, and reduced the amount of nodes as much as possible
also run it on its own thread
It's still usable with multiple destinations, you basically just have overlapping fields, and the unit uses the one for the destination it cares about
as long as the number of units reusing the field is high it can be worth it
yeah its good for the rts select like 100+ people send them to one area
using a mesh or quad tree really cuts down on the node count
over evenly spaced grid
and A* and Dijkstra's do not care what the data is, as long as you can get your neighbors, and the more convex space you can represent with 1 node the more you can rely on stuff like local avoidance while also reducing the amount of nodes that need to be considered even for getting costs for every tile
Hey guys, I'm trying to get this system of re-orienting a 2d isometric object to work. It works by containing 4 sprites of the same object in each cardinal orientation packed onto the same GameObject.
The problem is, the update function doesn't seem to work:
public void setOrient(int orient)
{
tiles[this.orient].color = Color.clear;
this.orient = orient;
tiles[orient].color = Color.white;
}
When I run this code the tile stays transparent
Are you setting the Transparency / Alpha?
yes
I don't see it.
Sorry I didn't know the enum supported lower cases.
Debug to check if you're on the right tile?
I mean in code.
oh
tiles[this.orient].color could be referencing a null?
ah. Pretty sure that isn't. Because it's referenced in the start() function
and it doesn't throw a NullReferenceException
Drop a bp
bp? Sorry, I must be terribly new at this
Breakpoint.
ah
ok
ok. So I just figured out how to debug mode. Thanks
hmm, I'll fiddle with it on my own for a while. Don't want to eat up too much of your time.
how can I replace the skybox material in a custom render feature?
I need to sort this out.
Is there a way to declare a vertex on a mesh as an "anchor" and reposition the mesh relative to said anchor point?
I've way too many hours trying to position this procedurally generated mesh and my everything hurts
subtract the anchor vertex position from all vertex positions, no?
Oh, that would make the anchor position 0,0,0
That makes sense
Excellent
Thank you β€οΈ
This is a code channel, for advanced code questions. Delete from here and ask in #π»βunity-talk - though you'll be better off posting on the forums with that question
Ok, thank you
Hello, have question, trying to implement creating of scriptable object with inheritance yet unity doesnt know what to do.
Anybody tried something like this? What am I doing wrong
Error happens when i create scriptable object and try to drag it to object with Test script
What's the file name where class HelmetSO is declared?
When you select the HelmetSO file in Unity, and look at the Inspector, do you see the code or not?
Setup looks good to me
yeah, i did initially put everything in Test script and split them after error into these files, but refresh should have handled that.
maybe some reset unity functionality to rebuild it?
Yeah, it's weird that it says "None" on the SO instance file
Delete the SO (not the instance, the class itself) and re-create it to force a complete rebuild
Yeah, it fixed the problem, thanks hahahahah
I am trying to add the burst compiler to Unity 2019.4
I downloaded the "2019.4 Verified" package, and I get 5 errors. Each of them are the same but for different systems.
Basically it complains that I don't have XboxOne, XboxSeries and PS5 in my list of build targets.
Library\PackageCache\com.unity.burst@1.7.4\Editor\BurstAotCompiler.cs(259,47): error CS0117: 'BuildTarget' does not contain a definition for 'GameCoreXboxOne'
Does anyone know what version does not have this problem?
Because it's quite silly it's "2019.4 verified" yet requires build targets I am not actually going to build for
When using INetworkSerializable is there any difference between doing it these 2 different ways (examples are different structs)?
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref firstname);
serializer.SerializeValue(ref lastname);
serializer.SerializeValue(ref number);
serializer.SerializeValue(ref heightScale);
serializer.SerializeValue(ref widthScale);
serializer.SerializeValue(ref speedScale);
}
or this
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
if (serializer.IsReader)
{
var reader = serializer.GetFastBufferReader();
reader.ReadValueSafe(out name);
reader.ReadValueSafe(out color);
reader.ReadValueSafe(out logo);
reader.ReadValueSafe(out players);
}
else
{
var writer = serializer.GetFastBufferWriter();
writer.WriteValueSafe(name);
writer.WriteValueSafe(color);
writer.WriteValueSafe(logo);
writer.WriteValueSafe(players);
}
}
The first seems cleaner and shorter, why would some examples do it the second way?
What if you don't wanna work with refs?
Is there a reason you would not want to use refs?
A ref is not always desirable because of mutability.
Some times you want to keep things local, other times you want to work with references.
It really depends on your use case I'd say.
good APIs leave the lower level options open for people who have very specific needs
βοΈ
There is also a lengthy explanation here on ref vs not ref https://jonskeet.uk/csharp/parameters.html
In most cases you'll never actually need to use ref
It has some nice use-cases, but it's rarely actually needed
Hi, is there a reason my Quaternion only produces half of the required rotation here?
Why are you trying to construct a quaternion manually
Because every solution I've tried for my problem results in Gimbal lock, or undesired rotation
Has anyone used babylonjs?
I'm trying to figure out how to convert the angles of the camera there into unity
Looks like Z there is facing the other direction
but can't seem to figure out how to convert the angles
any help would be greatly appreciated
@digital helm would need to figure out what the up and forward axies are
then also if its left or right handed coord system
this is not how you make a quaternion
what are you trying to do
rotate whole character around the tetherPoint
I've tried lots of diff things, AngleAxis makes the rotation bug when the Axis changes, using Dot makes the character spin like that when the Vectors are completely opposite
rotate around in what way
that's pretty vague
what's the "tether point"? Is that where the rope touches the platform?
so the play should be able to hang parallel to the rope attaching it to the tether point which is where it intersects with the platform
so it needs to rotate on X by Vector3.right and Y by Vector3.forward
and then if I try to get the Angle from 2 Vectors, when I combine the rotation it's just completely wrong
there might be an asset store asset for this. have you checked if Kinematic Controller has this kind of effect?
ref Quaternion currentRotation and constructing your own Quaternion suggests that there are
so many bugs
that some of them are interacting together
to produce positive (expected) effects
so it's going to be a lot of back and forth of us saying "well what if you fix X in your code" and you're going to say "no that breaks Y"
"i just want this to Z"
AngleAxis makes the rotation bug when the Axis changes, using Dot makes the character spin like that when the Vectors are completely opposite
this is because there are so many bugs, changing any one thing in isolation breaks some unintended interaction
basically your code is this scene in the Simpsons right now @pulsar tundra
just been stuck on this for so long
there are so many bugs they are in perfect balance
@pulsar tundra well you can always rewrite things
programming isn't VFX, you can't just tinker and layer on things until it works and then you ship it
it sounds like you want to have a 3d game where characters tether to a platform and swing around it
and you have a specific opinion of how the tethered versus untethered (free fall) behavior should be
@pulsar tundra if you want the tethering to behave naturalistically, you can use the physics engine to get this effect
would you describe the desired behavior as "naturalistic"?
its y up and right handed system
not 100% sure how to check the forward axis tho
but i think its Z
yeh, literally everything else i.e gravity, collision etc works perfectly I just dont understand the rotation and how I'm gonna make it rotate correctly
rotate whole character around the tetherPoint
what does that mean?
in the video you shared, you're showing a character moving about a tether point
i can see why you're using the word rotate
but there's rotation and rotation, you know what i mean?
are you trying to make the character move naturalistically by moving the character around the surface of a sphere centered on this tether point?
or do you want Physics to do that for you? @pulsar tundra
it isn't clear from your code or your words what you want
do you want to orient the player model a certain way?
the code snippet doesn't tell us, and you haven't told us
so we're confused
yes, the character should rotate around the surface of a sphere towards what I believe is its tangential velocity, perpendicular to the radius
there's physics and then there's Physics
yeah I get that
so why aren't you using Physics to do that?
well im using an Asset for the character controller like you said
okay
okay well here's how i would do this with code, without physics
the tether point is the center of my sphere, the length of the tether is the radius of the sphere - it looks like we're assuming the tether is of a fixed length / rigid, which is fine
i would draw a vector from the center to the player's current position. then, i would rotate that vector by a small amount: the angular velocity * Time.deltaTime, whose units work out to be a small amount of rotation.
that's pretty much it
the resulting vector is the new position
as soon as the tether is disconnected, i would transfer the angular velocity into Physics velocity
right I see
i would not express angular velocity as tangential velocity
as soon as the tether is connected, i am assuming the tether is 100% rigid, so i will assume that the amount of linear momentum that gets turned into "angular" momentum (angular with respect to how i am simulating this, which is the rotation of a big sphere)
looks something like
angular velocity = Vector3.Cross(tether vector, velocity) / (length of tether squared)
this will correctly result in a lower angular velocity of this big rigid sphere i am rotating
if the tether is longer
is this helpful?
yes this helps a lot thankyou
you got really into the weeds i think with the code you already have
so the gist is
when my tether connects, transfer all of my momentum into the rotation of a big giant sphere centered on my tether point
and we are solving for angular velocity in the equation
tangential velocity = (angular velocity) W cross (position of point on this sphere) R
tangential velocity = instantaneous particle velocity at moment of tethering V
okay that makes much more sense now
i wouldn't describe this as physical
it is sort of naturalistic
it's really very gamey
but based on the video you shared that sounds like it's what you want π
imo, you should actually place a rigidbody into the scene that models the sphere
whose mass is the player's mass
or whatever
and actually transfer the momentum
and this way you can still do it with Physics
okay yeah I'll give that a go too
with the right collision layers it will work π
you can also... do the actual tether
but it sounds like you don't want totally physical behavior
an actual rope would behave weirdly*
even this approach will behave surprisingly sometimes
like if you have a very small angle between your current velocity and the moment you connect the tether
in real life, the rope would bunch up
in this, you will suddenly go into a sphere moving very very slowly
yeah I have an idea for some things like at the top of the swing I cancel out Velocity so that the player falls with gravity
i can do that now
just tryna get this rotation part down coz im so confused
I have a problem, im making a game thats currently on webgl, i want to show touch controls only when the player is playing on mobile, but not when the player is on pc or something else. How can i do this?
you can check if there's a touchscreen device available or not
I also think it would be a good idea to give the option to use touch or not when available because a lot of PCs also have touch screens these days.
Using the manual nav mesh builder api: Is it fine to use many instance of NavMeshData and adding / removing them from the global nav mesh, or does this have performance implications? I couldn't find anything in the docs
it works :)
Iβve got a question I hope one of you fine programmers can answer. In games that feature procedurally generated worlds, like Minecraft or No Manβs Sky, is the world completely generated at launch and held as data which is rendered only when the player reaches a certain proximity? Or is the creation and rendering happening simultaneously?
second answer
Interesting. As a follow-up, would the first scenario be possible, specifically in an engine like Unity?
Yeah sure, if the world is finite
The only general rule about what's possible or not is your hardware and the halting problem
both approaches are used, it depends on your goal
those 2 examples use the second approach
Can you provide an example that uses the first approach?
first one would take a lot of memory
way too much
I would use the first approach to eg save it on disk if loading it from disk takes less time that computing it
uhh WorldBox I guess
maybe Terraria, not sure though
terraria generates and saves the whole world at start
terraria has a lot less to save because the world is 2d and finite
You also need to generate it full if you need some sort of consistency between each part of the world
if some part depends on another then you kind of have no choice
So in theory one could generate the world on initialization, saving the mesh and object location data in arrays and sub arrays, storing those on disc, Then allow subroutines to access and alter that data at runtime?
Yeah but be careful, disk is expansive
well if it's optimized enough
you probably don't want to save the mesh, but only the data, like heightmaps, biome maps, things like that
and generate the mesh at runtime
maybe I am miss using the term mesh. What I mean is the matrix data and world position locations. Is that not just an array of numbers that can be stored and accessed relatively inexpensively? I apologize I know Iβm posting in the advanced code section, with admittedly not an advanced knowledge of practical coding.
Depends what you mean by inexpensively, you can check your disk throughput if you wanna know precisely
mesh is basically the 3D model of your world
the terrain, specifically
in the context of my message
No "infinite" procedural world type game would sanely use the first approach. it's a ton of wasted processing and storage for little gain.
There are lots of games that generate a relatively small procedural world at the start of a game session and use it for the rest of the game, something like Deep Rock Galactic would be an example of that
Or Factorio
But Minecraft and No Man's Sky are in a different category - since their worlds are "infinite"
I guess I was under the misconception that those games werenβt actually infinite. Just perceived infinite due to the sheer size.
they aren't actually infinite but the limit is not that there is some world size that was pre-created, the limits are just the limits of the computer to represent numbers accurately.
like you have coordinates in a minecraft world on x, y and z. But the world uses floating point numbers to represent those coordinates, which have practical limits as you get too far away from the origin.
Ahh. So as the player travels farther, more world is generated, to the point that the data size can no longer be handled.
something like that yeah
Minecraft is like, 5 times the size of the actual earth right
No way to store all that, really
You run into both storage limits and floating point precision limits with minecraft
since the generated chunks are actually stored on disk
That's why the generator used to go haywire when you reached the higher numbers right
Not sure I'm familiar with that particular phenomenon
since floating point precision falters as you reach certain number
When you got to extreme numbers it used to generate like this
Fascinating
with a 32 bit engine 16k x 16k meters is typically the limit of a game map that you can explore without any significant glitches due to float imprecision at human scale
That's.. a minecraft world is 60 million meters wide
to have a map of that size you need to have a moving origin
assuming one block is 1m
yeah probably floating point precision issues
the minecraft generator failing is probably just an artefact of their perlin noise implementation that breaks down for large numbers but could be easily avoided by using a 64+ bit implementation
wdym local?
like, the value of an area is just dependent on the local values surrounding it
if you generate a 60mill unit map you sample that noise at x = 60mill and ofc it has float issues there, since you cant represent 60mill accurately in float
Yeah, that's what we were talking about
but you could just use a higher precision floating point type and be fine
or use multi resolution sampling
Local as in the range is connected to the neighboring vertices.
yeah, so having a four billion wide grid wouldn't make the perlin noise strange
like it's not inherent to the algorithm
well, mathemateically no, but every implementation will have this problem inherently