#archived-code-advanced
1 messages · Page 48 of 1
If you are interested in learning more about the low-energy side of bluetooth I suggest looking into what GATT is
i know someone whose research was all about trying to achieve with a $500 sensor some of the capabilities of a $200,000 sensor, and it was a colossal waste of time, in the opinion of all the people who actually knew anything. it was laypeople like me who thought that was impressive
there's nothing to "learn" in that context
it's hard to express what i'm getting at
you're doing this for a class. learn the best and rightest thing.
especially if you're using unity to do anything. you won't have the intellectual bandwidth for jank
i would connect over wifi lol
i would probably change a few decisions here. that's part of the learning isn't it?
Yeah, Uni does not work like that often here.
But I can ask if swapping bluetooth for wifi is fine (best scenario would be to have both probably)
and yeah, you're right, probably doing stuff in unity, for the purpose of visualization, is more impactful than a command line program, although it's hard to tell since i don't know what the details are
Still, Wifi would have issues with lack of a local network when presenting the project
What do you want to learn? Is there anything particular?
Unity here probably won't change the grade. It's a mobile app class after all, but that's beside the point
What I need to learn is how to make mobile apps.
What I want to learn is how to make the phone and the laptop talk to each other as that's handy and also something I could use in the future in games
i suppose you would click "Create a Network" in a mac, and connect your phone to it and move on
if it's a phone, i suppose it would make most sense to communicate over the internet, which is what most untethered devices do
Actually... 🤔
That might also work on my phone. Not sure if the networks are separated tho. Would have to check that
your android app could literally poll an http endpoint
that your unity app writes to
that's more representative of the real world than anything else
While yes, internet would be the best approach. It also does not get me many more points on the grade. Which is why apart from the internet connection, it would be beneficial to also learn other ways to connect
Via a local network, bluetooth or even a cable
Yeah, that would also for sure be too slow for my project
hmm
i think you have a lot of requirements
that you haven't thought about
how much do you want to learn lol
you have a passion for unity
The project has basically the structure of "the more the better"
that's what this forum is for. obviously the best engineers don't go into glueing shit together that is owned by people too broke to do things the right way*
So throwing in more features and things equals better grade
hmm
what do you want to learn
What I want to learn is how to make the phone and the laptop talk to each other as that's handy and also something I could use in the future in games
this?
generally the best way to do this is to (1) not make a networked game, (2) communicate over the internet to a centralized server, finally (3) an ordinary local network
what's interesting about (1) is when you don't make a networked game, you can actually still have multiplayer, and you can even have multiplayer with not locally located people
Connecting phone to a computer is something I would probably use for more interesting controls for games. Like a space game that uses a tablet or a phone to display a dashboard or something along those lines
So I would opt for (3)
no, you'd opt for 2
Why? That would add needless internet requirement, latency and so on
What's the benefit?
for example, displaying a dashboard... that's going to be a website (2). if you wanted to show unity content on an ipad for a game played on your computer, you'd use something like sidecar, which is (1)
Ease of development
No, not really
well sidecar is a feature on ipads that lets you use the ipad as a secondary display
and accept inputs
you wouldn't need to "network" anything at all
How is that simpler to develop considering you have to also worry about a server and you need to have an internet connection
you would run your unity game, and it can render to the ipad
and to the monitor
does that make sense?
it would be 1 process
Sounds like pretty limited solution if it only works on iPads
do android phones suck? yes or no
simple yes or no
No
does every bluetooth headphone except the airpod suck?
No
Bluetooth Audio 
you are still at the beginning of this journey
@undone coral you've got a lot of opinions
@bleak marsh I've actually done what you are looking to do
I absolutely hate Bluetooth on daily basis because Windows implements it in the worst way possible. But I still use Bluetooth headphones from Sennheiser because they are just good
I've used internet, OSC over LAN, BLE
it's a long journey
it really depends what you want to do
the journey to making good, fun games is long
it's so hard
it's hard enough as is
All at once or... 
Jokes aside, how???

one thing i am glad i don't deal with in my life is jank
i don't see how jank is going to help me make a fun game
not all at once, just varied projects over the course of a decade lol
First was photon where I networked a "controller" player and the actual player over the internet. admittedly overkill, but fairly easy.
Faster iteration mostly. After all, prototypes are inherently jank
anyway, i'm trying to share a colorfully stated point of view, that will hopefully open you up a little bit
BLE was not necessarily for mobile controller. We used it to triangulate position indoors, but it was spotty and inaccurate and bluetooth libraries are hit or miss
Did you use the beacon stuff?
yeah
i'm not sure what else i could do to be helpful. the specific thing you are trying to do, communicate over bluetooth to a kotlin app or whatever, is out of scope, you already know that, there isn't going to be any shortcut and it's not going to be worth pulling all-nighters to achieve because the payoff is too low
everything in the bluetooth ecosystem is bad
OSC over LAN was my favorite solution for controller
it is essentially vaporware.
So far from what I tried they were miss or miss for me.
Considering my budget of 0$ because it's Uni project, the library I found on git did not find my phone at all... which is a bad start
you like those blanket statements. real world is not as black and white.
well i'm not wrong
Yeah, for a "real" project, I would probably look into that. Or Wifi + Cable as two options as they cover the most ground in the best way possible.
But here the options are sadly limited
if jank doesn't matter - and it sounds like you don't know what i mean by jank - listen, use unreal
use Unreal and Visual Studio C++
I can also go with the jank solution of having a Arduino with BLE module hooked using serial over USB to a laptop... but damn, that's extra jank
go to Janksville, Vaporwaresylvannia
It is not, BLE has been too ingrained in phones for so long that if you got battery driven embedded systems, want to connect to phones and want to avoid having a bridge then Bluetooth is pretty much the only option.
@bleak marsh I really like this library: https://github.com/Iam1337/extOSC
Using a Raspberry Pi will likely be easier
i can't think of the last time i had to interact with bluetooth. the only bluetooth device i use is the airpods, and their implementation with phones is baically it's own protocol
i cannot stress enough how shitty it is
Maybe, but it so happens that I have an arduino sitting here and also there are countless of tuts on that
it doesn't make sense to* put any intellectual resources into learning it, it's negative ROI
uniduino was a good solution for arduino-to-unity comms
Just curious, @undone coral. Did you use any decent Bluetooth headphones with an android phone?
why would i use an android phone?
wireless headphones? there's a reason the airpods are what they are
don't you see
Apple is not exactly known for excellent antenna design in their products
Dunno, to "open you up your point of view"?
i've certainly used one in that sense... but i would never recommend anyone use it
and i wouldn't develop for it
it's negative ROI
they're shitty pieces of technology
and once you realize that, you know, the extra $100-400 you spend on an iphone or whatever, if that's what it's about, pays itself back very quickly
Yet Android has 70% market share. Clearly a terrible investment 🙂
I prefer Android phones over iPhones 
Hey, I am trying to put some cancelation logic between two async tasks. They run to essentially “open” and one to “close” I don’t want the states to compete so I have some tracked parameters they report to so one can pick up where the other left off. I’m finding that when I generate a cancelation token it’s always canceling wether it’s requested to cancel or not. What’s the best way for one async task to interrupt the other?
And also developing on Android is way cheaper that the phone's cost difference as I don't need a specific brand of computers to build for it :v
show code? !code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Developing on an iPhone app was 1-2 days spent fixing up the app everytime an XCode update dropped.
Won’t be able to paste exact code but I can give a better break down on what I’m actually doing let me write it up
I have Android, but I'm not against iPhone. My wife has one. Use what works best for you.
Also, looks hella sweet. Sadly a bit out of my budget for this project. Will keep it in mind for the future tho
ah, well I also used this: https://github.com/relativty/wrmhl
it's archived but maybe still works
@warped galleon Did you do any information sharing via camera + QR tags?
Will check it, I will probably give BT another go and then ask the teacher. And there is like 95% chance I will go that route
Nothing advanced. Love the idea though. I read a blog post about some guy who managed to embed an entire Snake game in a large format QR code.
https://mattkc.com/etc/snakeqr/, it was a video I watched https://www.youtube.com/watch?v=ExwqNreocpg
The example gif has an amazing jank energy and I love it 
That's the thing about research projects, they're not going to be polished, commercially-viable products from the get-go. They all start out janky.
Exactly, if you make a polished and clean prototype... you did something wrong
Bluetooth specifications can be found here: https://www.bluetooth.com/specifications/specs/
Not sure how valuable it'll be though as the documents there are gigantic
Yeah, I am for sure not crazy enough to implement bluetooth from scratch
GAP is the thing you probably what you want to know about to make your phone or laptop become discoverable. Found this link https://learn.adafruit.com/introduction-to-bluetooth-low-energy/gap?view=all
Looks like a pretty nice intro. There are other options for Bluetooth communication. I've only gone the GATT route myself. (Ok, I've also done BLE Mesh, but that's a different beast)
Good luck with your project ^^
Thanks, will try taking a stab at in once more probably and eventually I will fallback to Arduino as a BT -> USB translator
@warped galleon this is essentially the functions. I want them to cancel one another if conditions are met when calling. A simple example if a door is opening, and you hit close it just kind of stops opening and rotates back to being closed. This has a more going on as its driving shader parameters and what not but, i want deacctivate to trigger even if activate is still happening, and vise versa. What happens now is it kind of works, but sometimes if you are clicking back and forth too much, it misses the ramp up or ramp down because they are both fighting for shader parameters.
private async Task Activate(float duration) {
float timeElapsed = 0f;
float end = Time.time + duration;
while (Time.time < end) {
//Do the animation of shader parameters and what not
await Task.Yield()
}
state = state.ACTIVE
}
private async Task Deactivate(float duration) {
float timeElapsed = 0f;
float end = Time.time + duration;
while (Time.time < end) {
//Do the animation of shader parameters and what not
await Task.Yield()
}
state = state.INACTIVE
}
where is your cancellation token?
So let me show you how i implemented that one sec
Since the function is mainly staying in the while loop during the animation i put an if statement in there checking the token for a cancelation.
private async Task Activate(float duration) {
if(state = state.DEACTIVATING) {
deactivationTokenSource.Cancel();
}
activateToken = activateTokenSource.token;
float timeElapsed = 0f;
float end = Time.time + duration;
state = state.ACTIVATING
while (Time.time < end) {
//Do the animation of shader parameters and what not
if(activateTokenSource.IsCancelationRequested(){
return;
}
await Task.Yield()
}
state = state.ACTIVE
}
private async Task Deactivate(float duration) {
if(state = state.ACTIVATING) {
activationTokenSource.Cancel();
}
deactivateToken = deactivateTokenSource.token;
float timeElapsed = 0f;
float end = Time.time + duration;
state = state.DEACTIVATING;
while (Time.time < end) {
//Do the animation of shader parameters and what not
if(deactivateTokenSource.IsCancelationRequested(){
return;
}
await Task.Yield()
}
state = state.INACTIVE
}
something along those lines.
hmm I'm not 100% that would work 🤔 I usually just pass the token in as a parameter. I've never tried to close over the source itself.
I wasnt seeing cancel in the actual token, only the source.
Does the token have to be passed as a function parameter? or can it be part of the class that owns the async task?
These tasks live in the visual component, I am managing and calling them from a visual manager class
I'm not sure what a visual component or manager is, but yes, the token can be a field in your class. But it should be passed into the async method.
okay, ill comb this documentation and pass the token as a parameter
Question while we are on async as well, is await Task.Yield() essential in this use case? Im having a hard time understanding when to use it? I am calliing the activate/deactivate functions with await.
Typically, in this case, I'd do await Task.Delay(Time.deltaTime * 1000); because you're changing fields that won't have visible effects until the next frame. Less computation.
though I very rarely do async calls that touch Unity things because most of Unity's API is main thread only
and async methods could be run on a different thread
I started using async in place of coroutines because it seemed to make logic cleaner especially for complicated sequencing
So await task.Delay(Time.deltaTime * 1000) in place of await Task.Yield()? and why 1000ms?
I agree, but could definitely lead to hard-to-uncover issues. Just the other day we uncovered a bug with our async code that was trying to access Application.dataPath and the exception wasnt being handled so it was just a silent error with a hung Task
Task.Delay takes int milliseconds and Time.deltaTime is float seconds
I see how that could happen, I do try to be cautious about what i do with them. Its generally just to visual components or intitialization
Appreciate the help @warped galleon
One more thing on your original question: I would not try to cancel one task from the other. Instead, have the caller give both methods the same cancellation token, await Task.WaitAny, and cancel once one returns. @wide tusk
could you explain more about await Task.WaitAny?
(sorry, bear with me)
Basically, you put your tasks in an array and await the return of any of them
They're also a version where you can wait on all of them to be done, Task.WaitAll
I actually might be misunderstanding you. You want to interrupt the other if one starts.
Yes
so if its in the middle of activating, it will just deactivate from that point, and vise versa
right now they compete with one another and its a little janky
got it
I was thinking I could just break the while loop in each with a state check
so if deactivate starts while activating it will exit thhe while loop?
might work, I'd probably just cancel the source for the other before starting the one
so i was sort of close in that initial implement, i just needed to pass the token into the function instead of accessing one sitting in the class?
you could just check the cancellation in the while condition while (Time.time < end && !deactivateToken.IsCancellationRequested) { ... }
Do I need a new CancellationSource for each function? Or can I generate multiple tokens from one tokensource? Do i need to discard after use?
yes, one for each method. Source only generates one token
awesome, let me get this rolling, thank you so much
and yes, I believe after you cancel, theres no way to "undo" the cancel, so you'd need a new source
okay, ill do something like activateTokenSource = new (CancelationTokenSource) when i enter either state
set the token from that new source to a variable in the class for the other function to access
I'd reuse a class variable, just make new before I start one. Would probably require one more method before you start the async method
Haven't tried to compile, but this is the general pattern I'm talking about: https://gdl.space/sigacocude.cs @wide tusk
public float animatedParameter {get; set;}
private UniTaskCancellationTokenSource animating = null;
async UniTask Activate(float speed) {
await GoTowards(1, speed);
}
async UniTask Deactivate(float speed) {
await GoTowards(0, speed);
}
private async UniTask GoTowards(float target, float speed) {
animating?.Cancel();
animating = new();
if (target < animatedParameter) {
speed *= -1f;
}
while (!animating.Token.IsCancellationRequested) {
animatedParameter += speed * Time.deltaTime;
if ((speed < 0f && animatedParameter <= target)
|| (speed > 0f && animatedParameter >= target)) {
animatedParameter = target;
break;
}
try {
await UniTask.Yield(PlayerLoopTimings.Update, token=animating.Token);
} catch (OperationCancelledException) {
break;
}
// todo: otherwise, allow OperationCancelledException to propagate
// it's up to you how you want to deal with cancellation
// do callers need to know? do they need to know via a bool? an exception?
// nothing?
}
}
that's it
are you just trying to animate something?
you can use DOTween, it supports async and cancellation intuitively
the thing that has really confused you is having two different distinct methods. they're the same thing in disguise
i don't think you want exceptions though right? @wide tusk if you don't want exceptions, why are you using cancellation?
you can't use task.delay in unity
you can't use Task.Delay in unity. you can use UniTask.Delay
you can't really use built in Task methods for main thread work in unity before 2023.1.0a17
if you are using 2023.1.0a17 or later, unity actually imported parts of unitask and many of the flaws with their implementation have been fixed
you can read more about it here - https://blog.unity.com/engine-platform/unity-and-net-whats-next - and it's in the updated sources for unity
Does anyone know if there is anywhere that is teaching engine developement?
you can Task.Delay(TimeSpan.FromSeconds(2), Token.myCancelToken)
am i taking crazy pills? i don't think you want to touch Task.Delay in unity
why?
You 100% can use it in Unity.
no?
🤦♂️
what bugs did you encounter?
here's one for example - https://forum.unity.com/threads/task-yield-task-delay-0-hang.518045/
i have been saying a bajillion times that the built in Task is too buggy to use in unity
That's not a bug. That's how async works.
i am saying verbatim that the first version where it is similarly reliable as unitask is 2023.1.0a17 and later
you can ask unity
🤦♂️🤦♂️🤦♂️
Not a bug just because you cant figure out how to use it properly
guys please don't argue with me about this
there's a good explanation to that.. here's why
-
That thread was before Async officially supported in Unity
-
Task.Yield isn't the same as
Yield return nullin coroutine (most people think they're the same, which is NOT)
What would you do in place of cancelation tokens?
That thread was before Async officially supported in Unity
i'm trying to say the first version that async is going to be officially supported is 2023.1.0a17
it's in the example
to wait frames in async you must implement customYieldInstruction https://docs.unity3d.com/ScriptReference/CustomYieldInstruction.html
officially
guys please
i do use cancellation tokens in the example i shared with you. but it should be apparent that you can replace them with a bool. it really depends on what you are trying to do
is it an animation?
Not arguing with you when I have several large codebases successfully using async 😆
if you want a robust async implementation in unity today, use unitask
Yes
what do you think your holy UniTask does for waiting frames 😄 ... it uses Unity's customyield
anyone who comprehends the issues here will agree with me
I've heard great things about UniTask. Not a bad recommendation
okay, what are you animating? what's your goal? to wire up a click to open and close a door?
but dont say you cant use async in Unity. That's just spreading misinformation.
this was a great read, ty
and you want to interrupt a closing with an opening and vice versa?
@wide tusk did you read the snippet i shared?
@wide tusk this one - #archived-code-advanced message
Checking it out now
there are a lot of pitfalls with using cancellation tokens
CustomYield all over the place 🙂
that's UniTask
you can achieve 0 allocation like UniTask pretty easily with async 🙂
Are you worried about Unity's official async support including cancellation tokens?
yes and the sources showing their progress is here - https://github.com/Unity-Technologies/UnityCsReference/blob/master/Runtime/Export/Scripting/Awaitable.AsyncOperation.cs
although i think the wisdom of moving any of the implementation into the native engine, which they did, was very very very low
Yeah I think I’m just going to break the while loop if the other function gets called
you mean with a bool?
but you have to implement it how i'm showing
open and close door is just "goto(1)" and "goto(0)"
do you see what i mean?
I’m tracking state with an enum
Yeah I could make them one method
It’s mainly animating shader parameters based on input curves
it would only make sense if it were one method. a door opening and closing can be interrupted because it's smooth in between
it doesn't make sense to use an enum for the state
do you see?
the enum is complicating things
Yeah let me do some refactoring here
look really carefully at my snippet
It is a bit over engineered
Appreciate the examples thank you
I was using bools but was advised to switch to an enum
like it's useful for naming 0 and 1 but it isn't necessary. it's something for your brain but not for the computer. you already have Activate and Deactivate for your brain, the enum is redundant
you don't need the bools either
you don't need that. it's a float
because it's smooth. it's the t on your curve
and canonically you can choose "active" to be t=1 and "inactive" to be t=0, but you don't make a state
there's no state machine
it's interruptible. you want it to transition smoothly. so it picks up wherever it left off
Beautiful yeah
do you see what i mean?
okay cool
also use speed instead of duration @wide tusk . you can see my updated snippet
i authored a complete example
however, you should probably be using dotween
with unitask, you can await a dotween sequence. then it is as simple as
Not really a Unity question if I'm reading correctly? There was one guy The Cherno doing a devlog on his development of Hazel engine 🤷♂️
sequence?.Cancel();
sequence = DOTween.Sequence();
// this isn't exactly the API but it's very close
sequence.Insert(DOTween.Tween(value => parameter = value, target, speed: speed));
sequence.Play();
await sequence.WaitUntilComplete(); // or whatever it is
you probably want to use a tweening framework for tweening @wide tusk
DOTween is what everyone uses
Casey muratory, Jon Blow. (In their live streams) Not really teaching but the best resources you can get besides reading the seminal literature and knowing your CS fundamentals https://handmadehero.org/
That's his latest project specifically for game dev
Anyone have any nifty ideas for having non-monospaced text not "wiggle" by centering on the decimal point?
I could do two separate texts, one left aligned, one right aligned, use a content size fitter inside a HLG, but... was wondering if there were something easier
Use the tabular numerals of your font
I could do two separate texts, one left aligned, one right aligned, use a content size fitter inside a HLG,
this is exactly what i do 👀
tabular numerals...?
Good fonts have numerals that are monospaced but look variable and match the rest of the font
unfortunately textmeshpro does not have tab stops / tabs with alignment
hm.. ok, i'll dig.. i don't think this font does
so you'll have to jank it up yourself
the way you described verbatim
(you prob don't need a content size fitter)
i think editing the font to have tabular numerals is best for this use case since there's no non-numeric text in there (like "12.0 sec")
Code monkeys script
using System;
using UnityEngine;
using DamageNumbersPro; not working!!!
namespace CodeMonkey.HealthSystemCM {
/// </summary>
public class HealthSystem
{
nonsense inside this
}
}
Second script (my script)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DamageNumbersPro; Works!!
public class UltimateCrate : MonoBehaviour
{
} Why?
Why in codemonkey that using doesn't work
(no reference)
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
Sorry im new here
also #💻┃code-beginner
why are you in the advanced channel then
looks like you crossposted too 🤔
Are you sure that the issue is the namespace ?
We continued this conversation in #💻┃code-beginner btw
oh
Is there a sample generic DeepCopy<T> function that works without using BinaryFormatter?
I mean in a sense, Instantiate is a DeepCopy function under the right circumstances...
Is it actually? Does it copy member objects? Or just copy the reference to them?
It depends on the nature of the members
unity serialization doesn't handle Dictionaries in any case
Have you considered using a generic serialization framework
like newtonsoft JSON
or MessagePack
what's the use case?
I have. The object type I've been given is this container dictionary object that contains a bunch of sub objects that exist as json strings within the parent object, and are each deserialized into their specific types using newtonsoft Json deserialize<T>
so sounds like you already know how to serialize and deserialize this thing
no
the reason deepcopy doesn't exist is because it is a code smell
it's not like language designers all around the world haven't thought about this
Yes im stupid, just ignore that lol
what are you trying to do
Replace BinaryFormatter inside a T DeepCopy<T>(T data) function that currently works. ```cs
MemoryStream memoryStream = new MemoryStream();
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(memoryStream, data);
memoryStream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(memoryStream);```
Is that the DeepCopy ?
yes it is
I might be wrong, but it feels like a shallow copy
Why does it feel like a shallow copy?
I'm not sure, but how can you copy reference from inside your object ?
I have not work with MemoryStream/BinaryFormatter often
it serializes/copies the referenced object
this is a must for serialization - as the whole thing is meant to be written to a file or sent over a network
Yeah, I read a bit. Seem like it does the hard work of copying the nested reference.
Anyway, the internet as ton of answer to your question.
Do you really need to deep copy literally any type? Because that does seem like you have deeper problems.
Using JSON seem to me the best.
Otherwise, you can implement a Clone Pattern. Just extend your class with a Clone Interface
If you have the reference from the code
I've implemented ISerializable and my GetObjectData(SerializationInfo info, StreamingContext context) iterates through the dictionary to get the nested objects
Yeah, is there any issue with this approach ?
I have a custom type that inherits from a Dictionary<string, Dictionary<string, object>> and ISerializable.
That hurts. Do not inherits from that. Use composition.
BinaryFormatter is being deprecated. I'm looking for replacements
Yes it does hurt. It took a bit to get this ad hoc solution in place. My thinking is we should end up using necessary types instead of a massive dictionary
Did you try SoapFormatter ?
Composition, like you said
It is the same as BinaryFormatter
I did not try soapformatter
Could use some advice on generating a procedural world map. At the moment I have a heat map, a rain map, and a height map. I would love to create a biome map utilizing these maps. I thought of applying the height map first, offset the heat map from the height (higher = colder), then with the rain map i can determine the biomes from that
What do you suppose to happen if you DeepCopy(Debug.Log)?
At long term, you should definitely switch for something else though.
So, if you want to keep the code as is. You can choose other implementation of IFormatter and you could even re-implement it.
What I’m trying to say is that you do not need a deep copy that can handle literally any type, you only need some types to be able to be copied. You are probably having an XY problem, whatever you are using this deep copy for can probably be solved in much better ways.
what is the big picture thing you are trying to do
what are you copying?
I believe the initial plan was to send a complete copy of an object over to another process using a transport/messaging layer (currently using a socket via loopback interface).
Yo, do you have some own games on Steam?
I'm implementing a status effect/modifier system for a card game. I want to allow for status effects to respond to any action during a battle (drawing a card, taking damage, etc), including the potential to completely interrupt events. Cards also need to know ahead of time what the outcome of their action would be, for a nicer UI experience (i.e. if a modifier changes a card from dealing 5 damage to dealing 8, a card would need to know this so it can display "Deal 8 damage").
At the moment, I'm implementing this by creating before & after events for every action (e.g. DrawingCard, CardDrawn). When invoked, an EventContext will be created that allows subscribers to manipulate values and/or interrupt the event, sort of like a transaction. But this feels horribly clunky & requires a fair amount of repetition in listeners (i.e. if (context.IsCancelled) return).
I feel like I've approached this all wrong - does anyone have any ideas/examples of a better way to handle a system like this?
hmmm.... why?
spellsource and hearthstone achieve this by attaching conditions to an event on the queue. one of these conditions is whether or not the event queues at all, evaluated at the time it is queued by another thing like a card effect. the other condition is whether or not it fires / is still valid, at the time its effects execute. instead of deleting events, you can "mute" them.
it's kind of rare these things interact though. like events are uncommonly interrupted. you probably mean that they are evaluated depth first, which is true.
that makes sense. do you have some links for me? struggling to see how this would be implemented. my comp sci theory is also pretty limited so "evaluated depth first" is lost on me
https://github.com/hiddenswitch/Spellsource/blob/1b6eb8a616f99fded78cd248c694ae9bf76365ba/spellsource-game/src/main/java/net/demilich/metastone/game/logic/GameLogic.java#L5293
this will correctly work if fireGameEvent appears multiple times in the call stack
you can check out the hearthstone wiki hearthstone advanced rulebook for more details
this is awesome. i had a quick skim but plan on doing a deeper dive into this approach tomorrow, as well as checking out HS too
thanks 🙂
you can clone the repo with the instructions provided, run a test in a debugger in intellij and see exactly what callstacks look like
game callstack == java callstack in that codebase
yeah - im hoping to get some time tomorrow to proper crack into this
i’ll admit it’s disgustingly late but i’ve just sat here taking a deeper dive through GameLogic & also the HS advanced rule book - which was surprisingly technical*. Kudos to yourself and others who worked to make spellsource* so readable
i’m starting to feel like i should be separating what’s a modifier from what would be triggered by events. i can see how this is a much much cleaner way of handling resolving multiple unknown events, but none of that answers how a card can maintain an updated UI based on the battle context (i.e spell damage in HS, or the equivalent in spellbook) - which now seems like an obviously separate system. i’m sure i’ll figure that out once i’m a bit more stuck in, my brain’s pretty fried now
Card games are pretty lightweight, such you only need to update the UI every so often. You'd probably just want to refresh it between every phase, and every time a card comes into play.
Ideally you want to update the least amount possible per call, but I doubt it would be much of a performance issue just to update everything on the playing field.
Im trying to use Unity for a cross-platform desktop application,
Is it possible to build multiple scenes each with their own application window as a single .exe?
Or do I have build each scene as separate .exes and then package/bundle them together?
Theoretically, you can load all scenes additively each with their own camera and render each camera to a target display https://docs.unity3d.com/ScriptReference/Display.html
I'm curious what your use case is
Different windows means different player instances, so I don't think it's possible with one exe.
what are you trying to do
Maybe possible with unity as a library🤔
Could probably run several unity processes from your own app:
https://docs.unity3d.com/2019.3/Documentation/Manual/UnityasaLibrary-Windows.html?_ga=2.82179990.1212982720.1678411722-1569242621.1541837927
And you could pass in different command line arguments to load different scenes.
Ahh, oops. Not possible after all:
You can’t load more than one instance of the Unity runtime, or integrate more than one Unity runtime.
Here's a screenshot of what I'm trying to achieve: 4 "scenes" each with their own application window, packaged and ran as a single executable. I know this is definitely not a typical Unity build setup. If it's not supported I suppose I could build each window as a separate executable and then have a separate launcher and bundle 5 executables together. Thoughts?
I don't what your trying to do. Are you trying to make desktop with interactable "scene" images and each image is a scene you can go to?
The above is a wireframe concept, showcasing a theoretical desktop application built in Unity as a single executable with 4 scenes running in separate operating system windows communicating over IPC. I want to use Unity for this because these UI "scenes" will possibly render some 3D interactions.
My hunch is this isn't possible within Unity and I will instead have to build each scene as separate executables and bundle them together with a launcher executable. Just trying to confirm that with you folks as I'm no Unity expert 🥴
They don’t have to be separate executables, you can very well do it with one and give launch arguments to indicate which scene to show.
I do agree you should look into Unity as library instead, and build rest of the app with a technology that actually is meant to use for building apps, if your 3D interactive parts are concentrated.
Doing UI in Unity is, not good experience to say the least.
Gotcha, how would I show 4 application windows open simultaneously on the desktop, individually running 1 of the 4 scenes (window 1 -> scene 1, window 2 -> scene 2, etc?)
Or are you suggesting just use 1 window and switch between the scenes... thats not what Im after unfort 😦
Just launch 4 instances of your game and each displays different scenes.
Gotcha I think at that point it would make more sense to make each scene its own exe and then bundle them...
Or use something that’s actually meant to make apps, rather than Unity.
🤯 😜
Why not just run one Unity instance with multiple windows?
Not possible, unity is fundamentally a single window framework (the entirety of windows GUI is designed for single window apps)
How about that? https://docs.unity3d.com/Manual/MultiDisplay.html
Those aren’t windows
It’s a full screen signal to other displays and it’s annoying to work with
I see. Thought it was just multiple fullscreen windows
Might technically be the case, depending on platform but without all the events you’d need to make a window
Unity just doesn’t support the idea of another window or even the host OS in any but the most primitive way that is also not extensible
Basically unity is your OS (this is the idea behind most x-platform frameworks)
Sure. But at least you can make use of some windows dlls to change some aspects of your game window (e.g. make them borderless or move to a screen position)
For the main window yes
multi window apps seem to be a remnant of old MacOS design philosophy
You can also call native API to create your own window and pump a message loop, but at that point you are just reinventing the wheel.
There are merits in using Unity to make an app, especially if what you need from Unity is interwoven into basically every inch of the app so separating it out isn't a realistic solution.
But from the original question it just seems like the Unity part is pretty isolated, it could even be launched separately and not even embedding Unity as a library.
For the approach of each window being a Unity instance and using IPC to communicate, I can't imagine the nightmare of testing them or debugging them in or out of Unity Editor, while that's something you get for free using an actual technology made for doing it.
You could, in theory, make 1 Unity instance and have 4 additional process of whatever Application that would be in charge of the UI. You would use Unity for the render steps (No UI), while your other UI process would communicate with Unity with Inter-Process API.
Or they could just make windows in UI and render camera within each, input get directed to whichever's focused. Still unclear about the use case, so maybe this is a non-starter 🤷♂️
You could even make the player transparent if the goal is rainmeter-like widgets. Though that might make cross-platform support harder.
Hello, I am trying to make my chess board have a flip function. So I tried to rotate it's position by 180 degrees. That didn't do what I wanted at all. I'm not sure what the right approach would be, but I want everything to remain where it was, but just flip the board.
Try setting the chess board's RectTransform anchor to the center instead of the corner. #📲┃ui-ux
These are all tiles, and they aren't on a transform.
So I am trying to use the positions between 1 and 8 for my board.
With this image, is there a formula I could use to create the outcome of green becoming red, where my board is composed on positions between 1 and 8, x and y.
r.y = 8 - g.y + 1
what is the creative purpose of this?
if you want four "windows" in unity, create 1 full screen unity game and put 4 "windows" inside of it
i am not sure if it's supposed to creatively interact with the user's PC desktop / other windows. is it?
Hey, I have camera issues. I have two different cameras that serve the same purpose of simply displaying the game (2D), but they treat what they see differently, thus the need of two different cameras.
They don't see the same layers. The camera that sees the layer B is an overlay of the camera that see the layer A, so everything that is on layer B is displayed in front of everything of layer A.
I'd like to tell camera B, the overlay, to only display where the sprite renderers on layer B are not in behind on the sorting order of a sprite renderer on layer A, so that if an object on A is in front of an object on B, the object on A is displayed. Is this possible ?
Look. Here the blue robot is on layer B, and the red one on A. On the scene view, the red is in front of the blue because it has a higher sorting order on its sprite renderer.
But on the game view, the blue one is on front because the camera that sees it is displayed after.
I'd like to get the result of the scene view in the game view, while keeping two cameras that sees two different layers
I think it's something to do with depths, but I'm not sure what
Ok, and what do you mean by "they treat what they see differently, thus the need of two different cameras."? Easiest way would be using single camera, otherwise you'd need to deal with Z buffer
One camera is seeing things in pixel art, the other doesn't. I cannot use a single camera.
What do I need to do with the Z buffer ?
For starter disable "Clear depth" for your overlay camera
done
And you may need to modify your sprite renderer shader to write and test to Z buffer
I don't think sorting order would have any effect across cameras
so that would mean I'd need a specific shader for every sprite on layer B ?
You wouldn’t be able to use default one so yeah.
And keep in mind you would still have issue if your sprite is semi transparent
Can you explain to me how the Z buffer works ? Having trouble of settling the Shader
https://en.m.wikipedia.org/wiki/Z-buffering
It’s a big topic to explain in discord
thanks
In the unity shader graph, the Z buff er of a camera is just a single value. Should I read it as "The current Z-buffer - the previous Z buffer" ?
oh wait never mind
used the wrong node
Not sure if shader graph supports them well
¿Is there a way to get the internal id of a Unity Object? I mean, the pointer or number that they used to handle the C++ side of the object?
For example, in C# Job apis, many APIs of raycasting can return you the id of a collider and the collider instance... but it seems there is no user API to get the Id from an instance or vice-versa...
I have these 2 methods for Facebook Login in firebase , one just does login and the other links a users Facebook to an anononmous auth account how can I link once then use the regular Facebook login after?
https://pastebin.com/PB4E29eD
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.
anyone can help me?
There's Object.GetInstanceID(), but I don't know of any inverse function. Except maybe editor only.
for ?
realised i called spellsource "spellbook" last night - likely because i was thinking of the word "readable" 🤦♂️ sorry about that!
i've setup spellsource locally but i'm having some issues when running the test suite - its failing for the task ':spellsource-containers:createPostgresImage'. assuming I need docker installed to run the test suite?
also, another q about how the queue of triggers is resolved in fireGameEvent. after queueing all triggers, it'll start resolving the queue until it hits a trigger that fires another game event - at which point it will begin resolving that event. have I got that right?
yes you need docker to run the server test suite
you can run the tests in spellsource-git-cards for just the engine
it'll start resolving the queue until it hits a trigger that fires another game event - at which point it will begin resolving that event. have I got that right?
that's correct
because that's kind of how it goes when you read the rules text out loud
if you have a card in play that says "Whenever you draw a card, take 2 damage." and then you play a spell that says "Draw a card. Cast it."
you're going to draw. then, you take 2 damage. then the card is cast.
so if there were a piece of code
try {
var card = await DrawCard();
// cast asserts the card is not null
await Cast(card);
the call stack of taking 2 damage is going to have DrawCard() in it
async T<Card?> DrawCard() {
if (deck.Length == 0) {
await TakeFatigueDamage();
return null;
}
var card = deck.RemoveAt(deck.Length);
hand.Add(card);
await FireGameEvent(new DrawnCardEvent(card));
return card;
}
yeah that makes a lot of sense
async T FireGameEvent(GameEvent evt) {
var triggers = new List<GameTrigger>(GetTriggersInPlayNow());
var queued = new List<GameTrigger>();
foreach (var trigger in triggers) {
// you can order the triggers in a way that makes sense for people
// the two orderings are order of play and left to right on the board
if (trigger.ShouldQueue(evt)) {
queued.Add(trigger);
}
}
foreach (var trigger in queued) {
await trigger.Fire(evt);
}
}
abstract class GameTrigger : Card {
sealed bool ShouldQueue(GameEvent evt) {
// common rules
var associatedCardIsInPlay = !this.IsDestroyed
/// ...
return associatedCardIsInPlay && InnerShouldQueue(evt);
}
...
async T Fire(evt) {
await Play();
}
}
class CardDrawnTrigger : GameTrigger {
override bool InnerShouldQueue(GameEvent evt) => evt is DrawnCardEvent;
}
@kindred remnant does this make sense?
yes
triggers themselves can be a kind of card for the sake of simplicity
they are in hearthstone (so called Enchantments)
that's pretty much exactly what i got from the repo
if i were to redo spellsource that would be the case
however it would still need a "trigger" idea
its daunting doing this properly (esp looking at how mature spellsource is), but im determined to get this right instead of relying on some hacky list of events that instantly invoke and introducing a million bugs in doing so
but ye very cool, ty for the breakdown, makes a bunch of sense. looking forward to giving it a go
yes there's a lot of complexity. consider Battlecry: Give adjacent minions, "When this dies, draw a card."
this is why you need enchantments & game triggers as a thing
lots of cards put text on something else
re: your earlier question "how do i visualize effects"
you can do this generally the way Into the Breach does it, which is to play out the action. however that game is fully deterministic. you can show the results of a game action only if it does not call a GetRandom method or peak at private data at any time during its execution.
spellsource has this and it is complex
spellsource also has non side effects aware visualize that is pretty straightforward
since the number of cases for this are pretty low
this is a "glow" implementation on cards
and the "dynamic description"
yeah on paper that seems pretty straightforward. decided to leave that to the side for now and not try to bite off more than I can chew.
my previous attempt at this saw any enchantment that could modify a cards value stored in a dictionary on the BattleContext, with events for when their values changed. cards with dynamic descriptions would then fetch the updated values from there and stay synced whenever the values changed. but it was borderline spaghetti and often involved overly-complicated overrides
i rerender the text for dynamic descriptions on demand
card games aren't really performance constrained
what constitutes on demand?
Attempting to add Newtonsoft,Json package. But whatever link I put into package manager, add from git, I get the same result (and I’ve tired quite a few):
[Package Manager Window] Cannot perform upm operation: Unable to add package [ com.unity.nuget.newtonsoft-json]: Package name ' com.unity.nuget.newtonsoft-json' is invalid. [InvalidParameter].
I’ve been searching for the correct path for 30 minutes, with no luck. What is the correct path to install this package from git?
whenever the server needs to send an updated game state to the client, it recomputes all the card text descriptions
gotcha 🙂
have you tried without the whitespace
ffs - thank you
one of those days 😦
Hey, just attempting to see if what I detailed above is possible in Unity.
As for the creative purpose, there needs to be support for drag and drop (desktop folders -> the application windows) and saving to desktop, resizing UI, etc. So very much your typical "windowed" application requirements...
Looking at the feedback from you folks I think I might end up going with something more typically suited for desktop apps... as using Unity would be a square peg in a round hole.
what is the app?
like what's the idea?
i don't understand why you need 4 distinct windows. that's starch with low ROI
i understand why you'd want 4 windows, but not like, why you have to see the desktop in this particular way, instead of say how every other app does it, which could be windows inside a master window
you could still resize and see
my gut is telling me something something audio or something something creative coding...
so what is it?
Ha fine you got it out of me 🙂 its a kind of MusicOS. The 4 distinct windows are the "utility/productivity" aspects of the user story. The screenshot above shows the breakdown of each window.
There would be a master player window that opens a stream and another window that acts like Steam and boots unity apps that listen on that stream...
The whole idea is very hybrid and personally the exact solution I need for my purpose. So just a personal thing/creative coding yes, in other words no ROI required...
okay. so i think you do a master window and have smaller windows inside of it. if it's important to you that things LOOK good, especially if you want 3D or any kind of realtime visualization, you should use unity. keijiro has lots of live audio examples that will be essential to you
it seems like a mistake to focus too much on, there is desktop in between the four windows. that is not essential
you can have four windows inside your game window
need for my purpose
what is the purpose? can you give me a concrete example? it's the "boots unity apps that listen on that stream" part that i am confused about
I've been trying to bitpack some data into uvs with mixed results, someone suggested using custom vertex attributes but I'm struggling to get my head around them. Does anyone know how they work?
I'm finding that if I add new data with SetVertexBufferParams the old data vanishes, is this right?
what is the effect you are trying to achieve
I'm combining a scene with multiple materials into a single material, each material has different properties set so I need to bake the data into the mesh somehow
You make a compelling argument but the "essential" aspect is the app living within your workspace/desktop env... that completely changes when you have to boot fullscreen and cant intuitively work with the OS file management.
Unless what you are saying is the app boots fullscreen with a transparent background allowing for "click through" and the 4 distinct windows are inside that...? The issue then, is multiple display support.
The purpose is gamifying the reason to own a personal music collection. I dont really care to go any further but appreciate the curiosity.
i'm saying that the four rectangles live inside a resizable master rectangle
it doesn't have to be full screen
for example, photoshop lets you have four floating windows inside of it
and photoshop itself can be windowed
i think you understand what i am saying
i think you should look at https://github.com/keijiro https://vimeo.com/keijiro for inspiration for why you would want to use unity
in my opinion, when you are excited about something and get anchored on a really specific UX... unless you have been doing this for ten years and use a million bajillion apps
it's probably not as important or essential as it seems
but if it's only for you by all means experiment how you'd like
i don't think you'll have working sound if you try to build a native mac app from the get go or whatever
for a long time
did you look at the mesh combiner studio asset on the asset store?
yeah and the texture array one but neither worked quite how I needed
okay. in my opinion you might want to change your assets to fit how those tools work rather than the other way around
that would be nice but its too late now
it's not possible to combine meshes in the general case
I've got it working with packing to fp32
but run into errors with the special case fp numbers
I think vertex streams is my solution
I just feel like I'm missing some fundamental understanding of them
@undone coral Fair point about the photoshop example... curious how resizing would work.
Thanks for the links... thats very sick, that dude has a gift.
You make a valid case against UX-as-the-product or whatever so fair enough (funnily enough I have been building UIs for close to 10 years haha)
And yes its probably not essential but something I want... very badly and I dont have.
I think what ill probs end up doing is building the desktop app in tauri (uses rust and webview) and then just launch seperate unity executables with a steam like overlay.
uses rust and webview
well... it's your goals
there's a reason keijiro has so much output
and can go at this every day
with two weeks of work, you can start to make things in unity using vfx graph that look like Refik Anadol
it isn't realistic to achieve that zeitgeisty stuff if you are using rust
so it comes down to what you want
you will be dealing with too much faff
for example, I know a mesh is made up of mesh.vertices, mesh.triangles, mesh.normals, mesh.tangents, mesh.bounds, mesh.uv, mesh.uv2, mesh.uv3, mesh.uv4, mesh.uv5, mesh.uv6, mesh.uv7, mesh.uv8. Is that a vertex stream?
stream 0, can I just add stream 1 with new data and leave that all alone?
sorry for interrupting the other conversation btw
if you are experienced in yavascript, you should make a conventional electron app, and if you want nice looking visualizations, try p5.js
like loading an audio file isn't going to work for a while in tauri
you're going to get bored before you get something working
Not that it matters but you missed my point. I guess you dont know what Tauri is then or webview lol.
Again, appreciate the discussion but I think we arent on the same page.
i do
i know what these things are
the reason to choose unity is to make something that looks cool and is multimedia in interesting ways, at least with respect to Creative Coding with a capital C
you will have fewer engineering / technology choices and a very big ecosystem with which to solve problems
Agree agree, but thats not the argument.
right now i am not sure if the energy i am getting is aligned with "Exciting thing with music"
you haven't really told me what the thing is yet
i don't know if you know
the Opera of the Future folks, they give loglines like "it's an air violin" and it's just a bow and it's a motion sensor on the bow and you play in the air and music comes out
you know what i mean?
and they're music Creative Coding people
Haha I love the passion.
Look im all for the points you are saying but to be clear the choice of Tauri is for the Steam like launcher aspects that would boot and connect to Unity experiences.
^ clearly
that's very Radical Atoms
it's hard to do Creative Coding with UIs. they all wind up looking like "it's a bunch of nodes"
"it's maxSP"
especially with music
"it's Osu! but i haven't played it so i didn't realize i reinvented Osu!"
everything in 2d has been done
it's too obvious and too easy, and the million monkeys on a million figma typewriters out there
they've done it
Now this guy is just shitposting... is that against the guidelines?
lol
😜
no i'm not shitposting, i'm just trying to illuminate why it might make sense to Just Use Unity and Don't Add More Complexity
this is not a controversial opinion. adding more software is generally not a good idea
Hmmm no I think you have spent too much time in 3D.
Theres value in creating a stepping stone for productivity meets creativity.
Especially when the application is a mixture of managing an asset and "experiencing" one.
I'd say reinventing a UI framework inside Unity is more complexity than just using an existing solution made for UI and launch Unity for parts that need it.
i'm only speaking from the point of view of doing something innovative / creative
the Creative in Creative Coding
this is true, i wouldn't use Unity for 2D UIs
buuuut i wouldn't make 2D UIs. do you see
if you want to make 2d uis, figma.
"but figma doesn't make apps." exactly
The essence of all this is: making ui is a shitshow wherever you go unless you make the exact thing everyone else makes
The pitfall in your argument is the disconnect between the OS layer and anything you build in unity.
Sure a Unity app can have a file browser but its not as ergonomic as the native controls that play to Users intuition...
yeah, and if i'm going to go through the shitshow, i'm gonna wanna do something cool
i don't wanna shitshow to make white outline buttons
Unity is the OS
Fair points honestly.
like that's innovative UI for music
and i can see where you are going with "music os"
like just keep it there
just stick to that logline and see where it goes
I tried building that 6 years ago. Long journey.
lol
UGUI and UI Toolkit are hardly UI frameworks, they are more like libraries that only does the UI rendering and very basics of functionalities, they do nothing to help you structure and architect an app with any complexity.
UI Toolkit in particular is just HTML/CSS/JS but in Unity, except just like no one writes complex web frontend with plain HTML/CSS/JS but always with some framework on top of it.
long journey
i don't want to generalize too much about "sound people," i focused on keijiro because he's a sound guy and the stuff he makes is sick
They are ui frameworks, just not app frameworks like Qt, that part is handled by unity
and none of it is low effort, but it is done so quickly and well
it doesn't have to be abstract visualization
if it's retrocomputing amiga palette chiptunes energy - which is tripling down on 2D - that's cool too, that can be interesting
if it's macos Aqua teenager desktop computer energy
also good fit for unity
if it's maxsp... mediocre fit*
I suppose that does depend on where you draw the line for frameworks, but it has practically nothing I expect out of a UI framework, at least out of all the ones I've used and toyed with.
if the thing you associate with operating systems is "buttons and windows" that's very retro to me
and there's a lot of charming retro stuff made in unity
if you associate "pipes and filesystems and..."
It's not about what it looks like.
yeah yeah
like what is the emotional energy
pipes and filesystems and sockets and operations per second, if that's what you mean by music OS
definitely make a command line program in rust lol
@wide elbow is this helpful?
No thats not what I meant but I have the feeling your after an argument not a constructive discussion.
Luckily tho there was lots of interesting takes here. Cheers for that.
no no i'm not arguing
i'm just trying to flesh out this idea
and what you are specifically excited about
in a concise way
Id love to have a platform that could allow people like your boy keijiro to build any unity app publish it and
then I can run my personal music collection through it.
Thats basically the idea.
okay
so like a collection of, let's call them music apps, and they always require a .mp3
Yeah and the music apps are Unity or whatever apps that just listen for Stream of audio data. Skys the limit
do you build the music app inside musicos?
No
okay
Too complicated
the way i'd do this in unity is host the whole thing on github and make a structure for it, and anyone who wants to contribute would clone the project, follow some light structure and pull request it
the part with the windows seems unessential here
indeed it sounds like it's a grid of thumbnails and does not have to be more complicated than that
so the hard part will be the emotional energy you want to translate into a specific app, and my feeling is that's going to be easiest for you and other people if it's either pure yavascript or unity
Yeah I was thinking something like Steam workshop or whatever is easiest. Github sounds easy.
Basically I just want a place to cook up some dope musically themed visuals on a weekend and then run playlists through them.
I thought about connecting Spotify instead of requiring files on your system but I dont think I can get at the encrpyted audio stream
i think pure yavascript stuff will feel like Mr Doob
yeah
since naything that has to work for any general piece of music.. .it's going to be pretty abstract
unity will be high yield in terms of VFX per unit work
most music games are pretty abstract too
so this isn't saying much
Beatsaber, Geometry Dash, Osu!, Guitar Hero
compare to PaRappa the Rapper, which is not abstract at all, and makes it clear to you in the title about its specific emotional energy
Right but that leads to the Skys the limit aspect. I want to build contraptions that play the music.
Like one of the Unity apps could be my dream music garage and you walk around first person.
And then I could walk up to 3D models of crazy contraptions that control the music.
There would be art on the walls etc.
yeah
okay then definitely use unity lol
that sounds cool
you can look at all the Masaya Matsuura games
https://en.wikipedia.org/wiki/NanaOn-Sha many of these are not abstract
NanaOn-Sha (株式会社七音社, Kabushiki-gaisha NanaOn-Sha) is a Japanese video game company which created what is widely credited as the first modern rhythm game, PaRappa the Rapper. It was founded by Masaya Matsuura in 1993. The game's success resulted a spin-off called Um Jammer Lammy, which is based on guitar samples, and eventually a proper sequel, P...
https://en.wikipedia.org/wiki/Vib-Ribbon this is the most abstract one
Vib-Ribbon is a rhythm video game developed by NanaOn-Sha and published by Sony Computer Entertainment. It was released for the PlayStation in Japan on December 9, 1999, and in Europe on September 1, 2000. Although the original PlayStation version was never released in North America, the game was re-released on PlayStation Network in North Ameri...
but when you ask people music game or music app, they imagine something very abstract
nobody says PaRappa the Rapper
Vib-ribbon... what a cool idea... reminds me what I loved about Adiosurf... You could make both of these and add to my app.
walking around a garage with instruments... you're already excluding a ton of music people actually listen to. like Bad Bunny doesn't know how to play any instruments
No istruments in my garage
lol
well whatever it is
i think you see what i'm saying
trance music is sometimes literally someone hitting play on a computer
so it's very abstract
yeah it's sick
there are a ton of music games out there
The difficult aspect is loading the personal music collection... thats why I was thinking I could leverage a Steam like launcher that simultaneously lets you manage your music like itunes.
is it difficult though
are you aware of spotify-dl?
well you are now
spotify will tell you what the person is listening to
and it will Just Work
it is out of scope to write a thing that shows anything more than a list of tracks. it could also just take whatever you are listening to righ tnow. or a spotify uri
so my point in all this is to get outta the way all this other faff. if you wanna make a compelling Music.app, it sounds like it will be this very immersive thing with a naturalistic environment populated by stuff related to the song somehow
you know, you're only going to deliver that in unity
the last thing before i have to go is you probably want to make these things with specific tracks in mind if you want them to have character
i.e. not abstract
it is really hard to make a vib-ribbon
if that's what you wanna do, focus only on that
and you should listen to the vib ribbon music because its universe is not "everything"
anyway if you make any progress on this at all please ping me. i hope this was helpful
https://github.com/SathyaBhat/spotify-dl looks like an easy way to bridge the gap and I dont plan on monetizing so... I should be good 👀
I see your point in cutting through the UI faff and focusing on the experience. I tend to get very caught up in slick UI (im a design engineer at work lol.)
Yeah that all makes sense and are good rec. I think its back to the drawing board for me and strip down what im trying to get at.
Cheers for this deep dive. Ill be on here as I investigate more...
@humble leaf helped me remember the name of this game - https://store.steampowered.com/app/290510/GNOG/
"I was in love with GNOG the second I saw it"-Rock Paper Shotgun"Weird and wonderful..." -Polygon"This is such a joyful game, I'm not sure it's possible to leave it without feeling uplifted." -Destructoid"It's a kooky idea brought about with lots of style and verve..." -EurogamerGNOG is a playful puzzle game about exploring monstrous virtual toy...
$9.99
338
it's not a music game, but when i hear "intricate" but also "something 1 person could make" i think this
THATS SO COOL. Thats exactly what I would want to build (just one of those gizmos) on the weekend.
Heres another that could be cool...
procedural celular automota with initial conditions and rulesets based on the data in a song
or
procedural environments that use high and low points to change to feel the energy
https://www.reddit.com/r/generative/comments/pmbqhj/digiscape_forest_an_interactive_installation_made/
(minus the midi controller)
If I want to only save changes to a scriptable object by specifically calling a function how would I go about doing that? The idea is to keep unwanted changes in editor and during runtime from happening unless specifically done through a custom editor window.
Maybe something like this but only updating the public fields? ```
public class DialogSO : ScriptableObject
{
[HideInInspector] public string Content = "";
[HideInInspector] public List<DialogResponse> Responses = new();
[SerializeField] private string content = "";
[SerializeField] private List<DialogResponse> responses = new();
}```
{
Content = content;
Responses = responses;
AssetDatabase.SaveAssets();
}```
This is a mess, why do you have the data serialized twice? What's SaveAssets doing there?
I'd think it would make more sense to just instance the objects you don't want changes applying for, and then just writing that back if you want to
I have a private field that is accessable to the editor and a public field that is not. The idea being that I only update the public field when I specifically want to save changes to the Scriptable Object.
When the time comes to use the asset, Only the safe public field is accessable via code.
I cannot instance objects in editor mode. The idea here is to make my Scriptable Objects dummy proof. No accidental changes unless you press a big red button that says save me.
this seems wildly unnecessary to me - and I imagine not that easy to do, since you're going against a core purpose of a scriptable object. I'm trying to figure out why you want this?
if its simply to protect against unwanted changes, sounds like the kind of thing source control will help with
outside of that, an editor script that checks if you're in play mode and then just hides the fields will do the trick
I noticed that while checking some dialog data in a scriptable object I had it was really easy to create permenant changes accidentally. Copying certain lines ect. If I wasn't really paying attention it would be easy to make a change and not catch it.
I figured it out though. ```
public class DialogSO : ScriptableObject
{
[HideInInspector] public string Content = "";
[HideInInspector] public List<DialogResponse> Responses = new();
[SerializeField, TextArea(30, 50)] private string content = "";
[SerializeField] private List<DialogResponse> responses = new();
public void SaveData()
{
Content = content;
Responses = responses;
AssetDatabase.SaveAssets();
}
[OnOpenAsset(1)]
public static bool ResetData(int instanceID, int line)
{
var asset = EditorUtility.InstanceIDToObject(instanceID) as DialogSO;
if (!asset) return false;
asset.content = asset.Content;
asset.responses = asset.Responses;
return false;
}
}```
now the only way to make changes is through my custom editor window.
i get that, but with great power comes great responsibility ™️ . SOs give you the freedom to change/tweak values at runtime - if you don't want to do that, you might as well be using JSONs
also: [HideInInspector] public - why not just use properties?
For me, the attraction of SOs is the ability to make connections that aren't hardcoded. For instance, if I want to have my character data contain a sprite and I change the sprite path. It will break the connection of a JSON.
giving you visual confirmation that you've potentially accidentally tweaked something you didn't want to 😄
I'm not super sure how Unity works. I know that it serializes public fields and shows them in editor.
it doesn't serialise properties, which is the behaviour you want
I want both serialized but only one is the source of truth and accessable from code.
why do the public fields need to be serialized?
because if it is not then it will always be null defeating the purpose of having it to begin with.
Hypothetically in this use case, the private field does not need to be serialized but I don't know how to make it show in editor otherwise.
public string Content
{
get { return _content; }
set { _content = value; }
}
i have 0 idea why you think that will always be null
Isn't that what serialization means? The value will always be the default value you set unless serialized.
the value of Content will be whatever the value of _content is - which is serialized. it's the same thing
anyway, you've solved it
sounds like you're happy with what you've got
Sounds good. Thank you both for your time and help.
I need some advice on optimizing a hexagonal, tile-based world generator. I have a world generator (gen) that creates noise maps for heat, height, precipitation, and basic tree maps. The maps are generated pretty instantaneous, taking less than a second.
The issue is instantiating the correct tile prefabs (like a grass or sand tile) efficiently. I use a pooling method to instantiate the tiles right after the height map is created so it creates sand or grass tiles at a certain elevation. Right now it takes about 3 minutes to load a 200x200 world size. It takes about 50 seconds for 100x100. These load times are pretty consistent too.
What are some better optimization methods I could do? I can show code and create a thread if anyone is interested in looking at this with me
Right now it takes about 3 minutes to load a 200x200
how detailed are these prefabs? you have to implement an LOD system
what type of file should i use to keep data for spells in my game? I want to be able to read from them to create spells with different values
don't use a scriptable object for this
if you need a SaveData and ResetData method, you are in a bad place
if your world generation is based on predefined map, how about using four threads to generate 100x100 areas, divide and conquer
i dont know how to use job system and task, first thing i come up with is multithreading
What are some alternatives? Constraints are: modular, easy for a designer to edit if need be, and hard for a designer to mess up unintentionally.
what is the idea here? what is a "dialog"?
Large string "Content" paired with List<Response> "Responses". A response is a label, a list of modular Func<bool> "Checks" that finds out if the player is qualified to choose that response and a list of modular Actions "Effects" that are triggered on button press.
Actions meaning Action (as in X : UnityEvent<>)?
Yes
no. they are currently scriptable objects
okay
Example: ```
public class DialogCheck_Flag : DialogCheckSO
{
public Dictionary<FlagType, int> Flags = new();
public override bool Check()
{
var result = true;
foreach (var f in Flags)
{
if (!result) break;
if (!Game.Data.Flags.ContainsKey(f.Key) || Game.Data.Flags[f.Key] != f.Value)
result = false;
}
return result;
}
}```
potentially thousands.
these are hexagonal tiles. 6 sides for the base, 6 sides for the cap edge, 1 side for the cap.
so 13 sides. but this isn't the issue. the issue is the load time, not in game fps (yet)
hold on ill send a pic
roguelike but with a focus on story and choices.
it's okay i get it
okay. how do you think Slay the Spire stores its data?
If I had to guess, some external spreadsheet and custom tooling to interface with it.
Yeah. So my goal is to have large worlds (think 5,000 x 5,000). But at the moment, even a small 200x200 takes around 3 minutes which is pretty long.
no
it's all java code
there is no spreadsheet, serialized file, etc.
how do you think hearthstone stores its data?
Enlighten me.
they have an xml file that contains values like attack, hp, card text and a variety of renderable tags. then they have two card code implementations - one that is a LISP-adjacent scripting language like JASS/GalaxyScript compiled from a madlibs-style editor, and another i believe, possibly, plain C++ but i don't know that part
i guess my point is that the code is code
it's not code as data
okay what about XMage?
the biggest, most mature public implementation of magic the gathering
which is whatever, 15,000 cards now?
@severe grove how does this project store its data?
okay
so i really want your game to thrive
it's going to be too hard to do
to program in scriptable objects
I am mid switch to Scriptable objects. Previously I was using a database file and a lookup table. ```
public enum DialogType
{
...
}
public static class DialogDB
{
public static Dictionary<DialogType, Func<DialogData>> Data = new()
{
{ DialogType.None, () => new() },
{ DialogType.NewGame1, NewGame1 },
...
};```
it's not going to work
your colleagues are not going to be able to program in scriptable objects
you're going to wind up programming, and packaging a program inside a scriptable object, which is 99% of the difficulty, and they will do the 1% of dragging and dropping this thing onto this other thing for you
it is unusual to have a dictionary of enum to functions
that is just a type. for example
abstract class Dialog {
virtual void Show() {}
}
class NewGameDialog {
override void Show() {
// you would just inline this here
NewGame1();
}
void NewGame1() { ... }
}
but then, you wouldn't need the classes at all
it is a function to save on overhead. I don't want to load all game data at startup. private static DialogData NewGame1() { return new Dialog_NewGame1(); }
you would just call NewGame() when you need to
okay
well
how far along are you?
do you have a playable game right now?
like a screenshot?
also have you looked at Ink for authoring narrative content?
are you trying to shuffle encounters, or procedurally generate encounters, or procedurally generate the spells?
Not of the dialog system. I do have a mockup from a older iteration that was a text based dungeon crawl.
I have a mesh
i want to put a hole in the mesh where a sphere hits, as if it goes through it
how could i do this?
look really cool
ii think i remember seeing this too
you should probably author the narrative in ink
which designers/authors do use and they do like
and keep the combat simple and arithmetic
it's going to be hard to program in scriptable objects / program in the inspector
i gotta go
Thanks for all the advice. Have a good one.
The object you're passing to the RoomChunk method doesn't have a Level0_Generator component
No, that's fine. Put if(generator == null) { Debug.Log(Objects.name + " doesn't have the component"); } after the GetComponent line
Show the entire error message
ok so the error is actually in the Level0_Generator script
The first error pops up when you use Destroy instead of DestroyImmediate. This happens if you run the code not in playmode like writing an editor tool
Anyone know why this highlighted part of my code causes the entire unity editor to crash
No joke this is what happens
How big is the json file.
I can't imagine it's actually big but it's worth a check
Not sure if it's related, but IIRC JsonUtility doesn't support top level arrays.
Well your JSON doesn't match Unit[] to begin with.
doesnt it?
No, it's an object with units of type Unit[].
Yes, that is why I put Unit[] into the FromJson function
No, it's not Unit[], it's an object that has Unit[].
oh okay, so I should make another class called like UnitList that contains one array which would be units of type Unit
Sure yeah.
alright
Well it's still odd that Unity would crash completely rather than just throwing an exception, feels like a bug.
thanks, its working now
You guys tried yaml over JSON? Are the file sizes smaller or bigger?
Size doesn't matter, if you care about size you can just gzip it and both will compress very well.
(If you can't compress, I would still assume they are similar in size, JSON is more verbose but YAML has mandatory whitespace requirement)
YAML relying on indentation to know what belongs to what, it's bigger than JSON in its short form
Wait didnt know you can compress them with gzip. Thanks for the huge tip.
Well I have a big level editor in my game and the file sizes do matter there (mobile). (especially with backup files)
JSON can go on one line, YAML can't
The bigger problem of YAML is simply that the support is nowhere near JSON, you have to bring in your own de/serializer, while JSON de/serialization is available directly as JsonUtility.
I prefer the newsoft plugin or how its called. Somehow the JSON Utility was always really fragile when I changed the saving files while the other one just handled it like a champ. There are also some github plugins for patching deltas
Sure there are plenty alternatives to JsonUtility, and you will struggle to find the same level of support for YAML.
Yeah JsonUtility is good enough for basic stuff. Get into complex structures and it's not supported anymore
Thanks for the tips, really appreciate it
Wow the filesize got 50 times smaller. Is it save tho? Like I avoided Binaryformatter and chose json because it is more save to use and gzip is now a byte array 🤔
hey guys im a bit of a noob i would appreciate any help or documentation you can send my way! So basically the project im working on is an art gallery where im getting the texture from a solana wallet and applying it on preexisting frames but like the picture showcases the texture is pixelated , (modifié)
so this is my code that applies my texture :
—————
Texture2D texture=nftData.metaplexData?.nftImage?.file;
_texture= texture;
name = nftData.metaplexData.data.name;
logo.GetComponent<MeshRenderer>().material.mainTexture=texture;
—————
when i add something like " texture.filterMode = FilterMode.point; " it does go through and changes the filter mode . When i add " texture.Reinitialize(512, 512); " the texture in game becomes full black ;
any clue on what i could do would be appreciated
Wdym by safe?
it is more save to use famous last word 😃 ...
If it's corrupted, then after decompress it just won't deserialize.
The security issues with BinaryFormatter are of a different nature, it's pretty well documented and you can take a read.
"Could" it execute binary code while reading the byte[] from disk?
How do you think anything is ever read from disk? They are all just bytes.
I guess not since they list Binary Reader as save
Yeah true that
this is beyond my understanding
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Animations.Rigging;
public class MultiAimConstrantPlayer : MonoBehaviour
{
public Transform player;
public MultiAimConstraint aimConstraint;
void Start()
{
player = GameObject.FindGameObjectWithTag("AIAimPoint").transform;
aimConstraint = GetComponent<MultiAimConstraint>();
var sourceObject = aimConstraint.data.sourceObjects;
sourceObject.SetTransform(0, player);
aimConstraint.data.sourceObjects = sourceObject;
}
}```
code works, it automatically set player as sourceObject but in game it has no effect. However when I add it manually then it works as desired explain plss
The two fields are public, meaning they show in the Inspector and you're able to drag-drop things onto them to reference other objects & components.
If you did drag-drop, then the code in Start might be overriding their values.
I didnt
Then whatever you're trying to find with these Find and GetComponent calls doesn't get found, you'll have to debug a bit
Using native array for job burst, is there a way I could use memcpy from span? NativeArray.CopyTo and .CopyFrom does not have a implementations to handle span...
You can convert a native array to a pointer, and use that pointer to create a span.
I need to do the opposite. I need to fill NativeArray from a slice of span, so that the data from the sliced span can run through Job.
That can still apply. Once you have a Span of the native array (which is referencing the same block of memory), you can use normal span operations to modify the native array as a span.
Will give this a try, thought I was fiddling around with UnsafeUtility, but couldn't figure out how I could access Span's pointer.
I don't see why you'd need to. Once you have a span of the NativeArray (Unity 2022.2 has a NativeArray.AsSpan method), then you have two Spans, that you can use regular safe span operations with.
Like Span.CopyTo
I don't have a span of nativeArray, I have a span of actual array, Haven't check out Span.CopyTo method yet. Trying this out.
As I understand it, you have a Span with data in it and you want to copy that data into a NativeArray. But since NativeArray doesn't have any copy methods that accept a Span, you can't. But if you convert the NativeArray to a Span also, then you can use Span.CopyTo.
Is there any method to convert Span back to NativeArray? I have a job method that takes in a NativeArray.
Is this unrelated to the copying? Or are you wondering if you can avoid the copy altogether?
Avoid creating new array allocation actually...
You can use a Span directly in a job, also with Burst.
There's some extra complexity when a Span references a managed array that Unity handles for you if you use it directly, but you'll have to do yourself if you want to convert it to a NativeArray.
Did not know this, was suggested to use NativeArray, but if it can accept span, great! 😄
Is there any cost to this?
Nothing that's mentioned here:
https://docs.unity3d.com/Packages/com.unity.burst@1.6/manual/docs/CSharpLanguageSupport_Types.html#span-types
Hmm yeah, that makes sense. I guess you can only use it when it's created within the job. Then disregard what I said.
This might be useful for you:
https://github.com/stella3d/SharedArray
It's not Span, but you mentioned your Span wraps around an "actual array", which I assume you mean managed array. This will let you create a managed array that can also be used as a NativeArray.
Could I make a neural network ai, feed it the tilemap and a player position, as well as give it movement parameters, and reward it for the closer it is to the target, and theoretically could that make a neural network that would bypass the need to write pathfinding code?
I’m new to AI but I’m excited to learn this stuff and I’m trying to see the capabilities, as well as how it could help my projects 🙂
Theoretically yes, but it would be much, much easier to just write pathfinding with same or better results
but I guess it would be good for practice
Yes, but I need to modify a slice of the array collection.
I might just have to find a way to perform mem copy with size offset instead.
Span makes it so much easier to work with section of array collection 🤷♀️
So you're using Span to modify a slice of the managed array? And now you want to pass that Span slice to a job?
Because if so, you can still use the SharedArray package I linked. The Span will modify the original managed array, which then you can get a NativeArray out of through the SharedArray. If you only need to pass a slice of the array to the job, there are ways to slice a NativeArray.
How can you get pathfinding code to work in tandom with a combat ai?
Like I want my ai to be able to adjust its position like, say, to move out of the way of an attack or something
The ai still needs to be able to maneuver itself not just towards the target but to an advantageous position for it’s combat goals.
(2d sidescrolling fighting game btw)
Three things:
Event Listener - Implement a receiver for the enemy who is engage in a battle, then roll a chance (random.range > probabilityToDodge) - if true, call your animator to dodge, otherwise resume current state.
State Machine:
Usually this is what drives "Behaviour" of your enemy. Setting up a state machine stating exactly what the enemy should do under certain conditions. E.g. When the enemy completes the iteration of the state machine, you can write a conditional check to see if the enemy should seek advantage position or recover (Low health, disadvantage against player, try to flee)
Safe zones:
For path finder, you can setup area where enemy would treat "safe zone". If the enemy is low on health or wants to gain advantage over the player, then you would have to setup obstacle that would provide advantage to the enemy ai. Once you setup the obstacle, you'd need to write code to "scan" the area, filter by tags or layermask, and instruct your enemy to move there.
I said that those are found, then it is added to source to follow but in game it doesn't work
Thank you! 🙂
I’m using a behavior tree (node canvas) for my enemy ai as a state machine
So I think that would work pretty well!
Hey all. I'm making a roguelite card game and I'm currently serialising an enemy's deck/pool of available cards in an EnemyModel SO. I'm mainly just designing things for now (so nothing really interesting to show) - the cards themselves are just empty Card SOs - which was how I originally planned on serialising card data.
After earlier convos on similar topics in this channel and from digging around other implementations of similar games, I now think it would be less restrictive to use JSONs instead of SOs for cards. However, I'd like to keep my existing EnemyModel SOs - but the only way I can think to continue serializing the card pool (i.e. keep everything the same except how cards are serialised) is to have strings on the EnemyModels pointing to their card JSONs.
This feels a bit wrong, and I'm wondering if there's a better approach to the whole idea.
EDIT: some more context if its useful. the player will enter rooms, which then procedurally generates a room context from a set of rules for the given RoomModel (SO) they enter. These RoomModels contain a list of EnemyModel SOs used in the room generation. I like the ease of creating & testing new rooms using SOs which is the main reason I've wanted to go for this approach 🙂
Have ScriptableObject and JSON. Use your Scriptable Object to deserialize your JSON. But personally, I do not seem the advantage of having JSON over SO.
public class Card : ScriptableObject
{
[System.Serializable]
public struct CardDTO {}
public CardDTO Deserialize() {}
}
Where do I go to get help with a basic question?
JSONs will allow me to store all the rules and details encompassing the effect of a card. I'm largely using Spellsource (mentioned earlier) for inspiration, but as a basic example, a JSON looking something like this:
{
name: "Fireball",
description: "Deal 4 damage.",
target: "Enemy",
spell: {
class: "DealDamageSpell",
value: 4
}
}
will be deserialized into a CardEntity that contains an Action - which will correctly point to a derived DealDamageAction. Handling it this way will allow me to introduce new keys and have greater control in the resulting object created.
with SOs, I'm finding it hard to figure out how to do a similar thing
Although I'm realising now I can probably just expose these as strings in the SO and it'll basically be the same 😮
Instead of a string for the action, you should use an other scriptable object. This way you will be able to serialize parameters. Also, you wont be able to misspell an action.
If I do that, I’ll have to create SOs for each variation of an action
You could also use a [SerializeReference] if you do not want to create nested SO. That would be better than a string.
Even Prefab if you want the ability to have template.
i can't see how this would solve my problem - what would this look like? [SerializeReference] Action? I don't understand how this will remove the need to create a new Action SO for every action, derived action, and possible variants of any of those actions
well if i could do it all over again, it would look more like xmage / slay the spire. xmage mixes code with data in a .java file. the nice thing about the JSON is it's like a LISP, and making it work a certain way introduced a bunch of really useful constraints. a language theorist suggested that i migrate to Clojure for new cards, because you can round trip a clojure program to JSON.
spellsource (and magic the gathering) have a lot of cards and rules
there's a card that says "Wherever a spell draws a card, discard one instead"
if you implemented your spells as english-text-to-c#-functions, that would be implemented by having some global attribute, DRAWING_DISCARDS_INSTEAD set to true while that card is in play, and the DrawCard method would check if that attribute is true, and if it is, call Discard instead and return
this is how hearthstone works
if you implement your spells in a homoiconic language, like a lisp in JSON, you could write code or JSON or whatever - the representationd oesn't matter
then you turn it into a datastructure (like json), and you find all the invocations of DrawCard and you replace them with DiscardCard
and turn it back into a program
spellsource actually does both
@kindred remnant the reason this stuff matters so much is the roguelike card format... it's exciting to (1) remix spells (2) let the user factory-build into something really huge and complex
so introducing meta cards has the right legendary oomph that it might be worthwhile
this scriptable object thing, that's a really teeny part of the picture. it doesn't really matter how you store it. of course, programming in the inspector is horrible
so there's an effect in spellsource called SpellOverrideSpell, which takes advantage of metaprogramming. there's also healing deals damage, which is an attribute.
it does both.
there are lots of things spellsource ought to do better. you're already declaring a separate CardDTO, which is right*. you need an immutable versus mutable representation of your card
enforcing immutability is impossible ins pellsource right now
I had a look at xmage - each card has a unique .java file. one of the things i found fascinating with how spellsource handles this is that, bar a few exceptions, there is no specific file/controller for individual cards (which is how I have done it in the past). what makes you want to take that approach if you were to have a do-over?
im a big fan of STS and have gone through a fair amount of their dev Q&A's, but found it difficult to find any details about how they go about this. i did decrypt a few save files which helped a little bit, but not a massive amount
give us a sec, i'm digesting the rest of what you've written. like you said, the thing that makes this kind of game fun (and what im trying to achieve) is to get to a point where it's easy to integrate for the player to upgrade and manipulate cards, and potentially as a part of the metaprogression of the game. and all of that is very new to me
wise man once said something something "start of a long journey"
im a big fan of STS and have gone through a fair amount of their dev Q&A's, but found it difficult to find any details about how they go about this. i did decrypt a few save files which helped a little bit, but not a massive amount
the mods are really eye opening
they look almost exactly like xmage
yeah cards that replace words on other cards, essentially, feel New to me
we don't have that in card games because they're multiplayer and it's impossible to balance such a crazy thing
but in single player roguelikes they seem good
sounds like you want to make a roguelike deckbuilder! 😄
never actually occurred to me to check them out 😮💨 . going through some of the material now
I did a concrete example for you. The advantage that you gonna have over JSON or a string it is that you will be able to more easily integrate with Unity.
- You will be able to pass Prefab, Scribtable Object, Asset, etc. as value.
- Have every functionality Unity offer with SerializeField such as Redo/Undo, Copy Paste, Nested SerializeObject, HideInInspector Attribute, Range Attribute, etc.
- Use CustomProprietyDrawer
That being, said, you will need to provides a way to add values to the array. A Drop-down should the tricks. I am pretty sure there is a lot of asset that does this for you. You could even override the ReorderableList and add the functionalities directly inside the (+) buttons of the list. (Maybe Odin Inspector as good capacities ?)
[Serializable]
public abstract class Effect
{
public abstract void Execute();
}
public class DealDamageEffect : Effect
{
[HideInInspector]
public string name = "DealDamageEffect";
[SerializeField] private float amount;
[SerializeField] private GameObject otherValue;
public override void Execute()
{
throw new NotImplementedException();
}
}
[CreateAssetMenu(fileName = "Card", menuName = "Card")]
public class Card : ScriptableObject
{
[SerializeReference] private List<Effect> effects = new List<Effect>();
//Quick Way to Populate the array.
//private void OnValidate()
//{
// effects = new List<Effect>() { new DealDamageEffect(), new HealEffect(), new DrawCard() };
//}
}
thanks, i appreciate this! it goes against what you mentioned earlier:
Instead of a string for the action, you should use an other scriptable object.
The way you have it now is more what I had in mind. The above would have kind of defeated the purpose, as there would be SOs all over the place for each possible variant of an action.
I'm still clueless on the core issue, though. Unity is terrible at serialising derived classes, and I haven't quite found anything that satisfies.
anyway, like doctorpangloss mentioned - i can tell im getting bogged down by the details rather than just getting something going, but im really reluctant to have to refactor this down the line so its something i want to be confident in before i start
Using a Scriptable Object would still be better than using JSON. SerializeReference is even better.
yeah, it's more fitting to the rest of the project so I'd like to give it a go. but not being able to do the above is a deal breaker for me. the extent of my property drawer/editor capabilities is making basic buttons so - long journey ahead
Hi there, is there a way to get the hit point where a spherecast meets a collider and no collider?
What you mean by no collider ?
The "air"
How can you get a collision point with nothing ?
The drawn lines are the outlines of the tilemap, under the line is all colliders. Above it "air"
Well I need the point in the outside of the sphere that's on the surface of the tilemap
Not all the points that are under the tilemap outline
Basically the x where I put a red arrow towards
I do not understand what you want, but is Physics2D.CircleCastAll what you are looking for ?
Probably that cast yeah, but I'm not sure how to get the point that I'm looking for
I have an enemy and it calculated a trajectory to jump
It jumps towards the player, but this distance to jump is restricted by a max distance. If the player is further that the max distance it needs to calculate a target point at the given max distance
Yo do not need a SphereCast for that.
You need mutliple Raycast on the trajectory line.
The problem is, that the trajectory line is based on the target
And since I got no target, I can't calculate a trajectory
Because the original target is too far away
Clamp the vector between your target and you.
And it bases its force on the target, in order to jump high enough
Which vector
2s
If I clamp it, I probably get the wrong point
I tried it with a max distance on the x axis and then a raycasts from above to get that point on the tilemap. But then the actual distance will be more in cases where the surface is not flat
Because again, it calculates its forces and trajectory based on the actual point it needs to land on
It's probably a much over complicated system I'm using for this
You want a max distance combined with X/Z and Y ?
Normally, the max distance express only in X/Z
Only x and y
Yeah that's kinda the problem here
In the code that I used it was commented that it uses the max distance on x axis only, but the actual distance it uses is combined
It's like (target.pos - transform.pos).magnitude
And what this distance is used for ?
But if those are on two different y levels this would be a diagonal line right
That distance is used to calculate the forces needed
What are your paramters ? Angle/Velocity/Height/Distance/Time/Acceleration
Only an angle
And distance
To give upfront, the other parameters are calculated upon these two parameters
Because you have a target
Yeah angle and distance
But without target I can't calculate the y force it would need to reach it
private void CalculateForceToTarget()
{
var rigid = pathfinder.rb;
Vector3 p = pathfinder.target.position;
float gravity = Physics.gravity.magnitude;
// Selected angle in radians
float angle = initialAngle * Mathf.Deg2Rad;
// Positions of this object and the target on the same plane
Vector3 planarTarget = new Vector3(p.x, p.y, 0);
Vector3 planarPostion = new Vector3(transform.position.x, transform.position.y, 0);
// Planar distance between objects
float distance = Vector3.Distance(planarTarget, planarPostion);
// Distance along the y axis between objects
float yOffset = transform.position.y - p.y;
float initialVelocity = (1 / Mathf.Cos(angle)) * Mathf.Sqrt((0.5f * gravity * Mathf.Pow(distance, 2)) / (distance * Mathf.Tan(angle) + yOffset));
Vector3 velocity = new Vector3(0, initialVelocity * Mathf.Sin(angle), initialVelocity * Mathf.Cos(angle));
// Rotate our velocity to match the direction between the two objects
float angleBetweenObjects = Vector3.Angle(Vector3.forward, planarTarget - planarPostion) * (p.x > transform.position.x ? 1 : -1);
Vector3 finalVelocity = Quaternion.AngleAxis(angleBetweenObjects, Vector3.up) * velocity;
// Fire!
//rigid.velocity = finalVelocity;
// Alternative way:
rigid.AddForce(finalVelocity * rigid.mass, ForceMode2D.Impulse);
}```
This is the code used
Without limiting the max distance
float distance = Mathf.Max(Vector3.Distance(planarTarget, planarPostion), 20.0f);
Wouldnt that work ?
What you are doing is https://www.youtube.com/watch?v=tKrlchCio_k
Replace:
float distance = Vector3.Distance(planarTarget, planarPostion);
with
float distance = Mathf.Max(Vector3.Distance(planarTarget, planarPostion), 20.0f);
Well limiting the distance changes the whole target point
It calculates its up force and forward force based on the target point. If that's not on the surface it will try to jump onto a place that below it
This could result into jumping into the wall
Instead of on top of it
Not if your angle is adjusted for the wall.
How? Because the force won't be high enough, no matter of the angle
The force will always be enough.
To get to the target
It is the point of the calcul
The target point could be half way the wall. If I adjust the angle, the force will still be only half of what it should be
You adjust the angle before doing the calculation.