#archived-code-advanced
1 messages · Page 174 of 1
if i can i use gpu particles. its the easiest way
Oh wait you’re not the same person 😂
Question:
If I want to put data from a "Local Host" (Ampps) into my Unity Project, using PHP and mysql, and I want to graph that data, is someone able to help me find a way to do this?
I know it is possible, but I don't know how atm.
I guess you want to set a joboffer here? Or a collab question, not really a coding issue, as you dont have any code yet, right? Or did you try already something
Hi ! Is there anybody who's already used Zenject or Extenject here ? I was wondering if they are any compatibility issue with supports (pc, consoles, etc) i should pay attention to
I use Zenject/Extenject. The only thing you need to keep in mind is IL2CPP platforms. It works with IL2CPP, but some gotchas. I've personally never run into those issues though.
https://github.com/modesttree/Zenject#does-this-work-on-aot-platforms-such-as-ios-and-webgl
Ok, thank you for your answer 🙂
I am trying to use PrefabUtility.GetPropertyModifications to apply some overrides to a prefab, but I can't find any docs on how to actually do that with the PropertyModification results from this function, does anyone know of any examples of how to use it?
I tried creating a SerializedObject with SerializedProperty but it doesn't seem to be registering as a change
I'm trying to programmatically do this apply:
Question - I **think **a really simple one: I have a map editor in my game that saves/loads custom serialized binary files to Application.persitentDataPath; this works absolutely fine. But now I want to make a few of these files locally with my tool and then move them into Unity assets so I have a few "built in" game maps. As far as Unity is concerned, they're binary data blobs files - what to do with that is my domain and is already fully solved. I naively think I want to make a ScriptableObject to point at a collection of my data files but... what variable data type would I actually need to use here so I can drag and drop these files? I can't put FileInfo pointers in my ScriptableObject. I can't drag and drop byte[]... I want/need something that ultimately lets me get a stream I can BinaryFormatter::Deserialize from. Is there a variable type I can use in my ScriptableObject here for this, or am I just wrong thinking I even want a ScriptableObject in the first place to enumerate them?
I half-suspect ScriptableObject is wrong and I just needed to be pointed at a different concept to go open docs for 🤔
for posterity - someone just mentioned to me "TextAsset" which also awkwardly necessitates me giving a ".txt" extension to my files, but then I can get ".bytes" off them and deserialize the binary from there. That actually works and I can reference a few of these in my ScriptableObject. Definitely awkward but it is now solving my problem 👌
for clarity, that looks like this:
public class MapDB : ScriptableObject
{
public TextAsset[] Maps;
[System.NonSerialized()] private GameMap[] _maps;
public GameMap[] GetMaps() {
if (_maps == null) {
_maps = new GameMap[Maps.Length];
for (int i=0; i<Maps.Length; i++) {
var stream = new MemoryStream(Maps[i].bytes);
_maps[i] = (GameMap) new BinaryFormatter().Deserialize(stream);
}
}
return _maps;
}
}
^ I'm sure there's a healthier way, but... anyhoo.... 🤷
For safety, use:
using(var stream = new MemoryStream(Maps[i].bytes))
{
}
@untold magnet You can create a ScriptedImporter to import any file type into whatever you want. So you can get Unity to import your custom level file extension as a Scriptable Object.
But, you usually wouldn't be modifying the source file, like how Unity doesn't modify source audio and art assets.
Hey, it's a while I get this kind of errors (months now)
Library\ScriptAssemblies\RobocraftX.Blocks.Ghost.pdb: Copying the file failed: The process cannot access the file because it is being used by another process.
I didn't care about them so far, but in 2021 they are considered compilation errors and prevent the application from starting in editor. Do you have any clue what can it be? The another process is unity itself 😦
Hello , how can i create a funcuning computer in my game , i wanna put "wikipedia" for search details for a person ?
I am
You need to read #854851968446365696 if what you're trying to post is code
I'm puttin my code between ''' '''
The bot removes unformatted code and you'll end up muted if you do it too much
Wrong ticks
Hi, I am trying to have a transparent background on a WebGL build with URP.
I have tried this solution :
glClear: function(mask)
{
if (mask == 0x00004000)
{
var v = GLctx.getParameter(GLctx.COLOR_WRITEMASK);
if (!v[0] && !v[1] && !v[2] && v[3])
// We are trying to clear alpha only -- skip.
return;
}
GLctx.clear(mask);
}
};
mergeInto(LibraryManager.library, LibraryGLClear); ```
But it's not doing anything. I also tried replacing "GLctx" by "gl" to make it match the context but then I have some weird artifacts
Thanks I messed up...
Does anyone know where I can find the default glClear function so I could try and modify it maybe?
Does anyone have any very simply explained resources on how to rasterize a 3D model into voxel positions? I've done a lot of googling but anything I've found is either very poorly documented, or not performant enough.
I've been plugging away at this for a few weeks but I can't find a fast efficient way to say "this cube grid space is within the mesh = true"
Dumb question about c#:
Can I provide default implementations in interfaces, like I can do in Java? I tried in c#, but somehow an implementor is not seeing the main interface method, only if I cast to the interface.
(A as IA).defaultMethod()
Am I missing something?
how fine of a voxel reoslution are you going for? Could you just compute the rasterization once (with some slow/ inefficient known method), throw the results into a HashSet<Vector3Int> or 3D boolean array and just look it up later as needed?
Nope, in C# that's intended behavior for default implementations in interfaces, you'll always have to explicitly cast to the interface type to be able to access those methods.
Thank you 😄
instead of implementing the interface explicitly, you can declare it as a normal method with same signature.
public class A : IA
{
public void defaultMethod() { }
}```
in the above case, ``new A().defaultMethod()`` is completely valid.
But then I need to implement twice, wouldn't I? 😄
no
Okay. Sweet. I will try that out
Hey, I hope this is the right channel. I am networking a game and have setup an animator using Animancer. Basically, I have a 2Dmixer that receives my input direction (up down left right) and the animation time. The issue is that when the input direction changes the animations just snap to a different one. I want there to be a tiny interpolation in between for a better visual result. The issue is that I am not entirely sure how to achieve this with Animancer - especially as I control the animations using network time. Any ideas?
in networking you basically sync the "hard" values on a data object and then have an interpolator that applies them to a separate visible representation of the object. The simples way would be to apply some exponential smoothing like this (pseudo-ish code)
void OnNetworkTick() {
_newInput = GetInput();
}
void OnUpdate(float deltaTime) {
_smoothInput = Vector2.Lerp(_smoothInput, _newInput, 1f - Mathf.Exp(-sharpness * deltaTime);
animancerMixerTransition.SetParameter<Vector2>(_smoothInput);
}
does anyone have experience embedding lua inside their game?
@compact ingot that seems reasonable. What is the value range for sharpness?
0 to infinite, usually up to 100 makes sense, values below 10 add very noticeable smoothing
my objective is to define an entire turn based game rules as something embeddable
Thanks.
so for example, a game loop that is a lua coroutine, which "waits for all user inputs" that may come from a single player unity game and a bot, or from networked users
This post explained making patches for an app.
How is this done? Do I need source code or can anyone make patches?
Whats the difference between a Task.run and a Async Task? without Task.run?
I am thinking one is on the main thread async task and runs concurrently by yielding and time sharing with the main thread. The other one lets us run a task on another thread
I think you're right elle
async Task and UniTask let you do async stuff within the main thread
Task.Run can use a background thread (https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.run?view=net-6.0) - when you say "Async Task" do you mean using async/await?
the scheduler then is in control over bouncing back and forth
Task is essentially C#'s promise implementation if you know the promise pattern, .Run has the work done on the ThreadPool. await implicitly creates a Task for the pattern, and does the work on the current thread
Is there a way in Unity to, say at compile time, gather all the scriptable objects of a particular type and update a field in a prefab with that list?
promise is essentially javascripts async / await though....
async / await is syntactic sugar around Task/Promise
you could do that with a source generator
probably
thanks! sometimes the hardest part is finding out the name of what you need
@stray pewter FindObjectOfTypeAll
if you look into source generators, make sure you're using the correct api, unity does not support even newish api levels yet.
that's at runtime
what is a "source generator"
@stray pewter actually, try AssetDatabase.FindAssets
you can use something like AssetDatabase.FindAssets( "t:YourType" )
primarily a lightweight program that reads all your code and generates more code based on what it finds. but it can also include and work on non-code assets. it's kinda like reflection but at compile time
that wouldn't work tho, bc he's trying to get instances of scriptable object assets, not the classes themselves
so FindObjectOfTypeAll / AssetDatabase is how to collect all the list I want, but where to do that?
ah, google was failing and just giving me the obsolete version
true. but as i stated, it can also include non-code assets. yeah, but maybe not the recommended solution for this kind of task
@granite viper thank you
@stray pewter the obsolete method group had a link to the updated interface
Gonna use bevy the superior engine
Hi all, I'm looking into making a server that simulates my game state and does hitbox/colision checks using a simple .net console app... I wanted to try to do it without a headless unity instance. Is there any sort of library out there for simple collision/hitbox detection I could use? I do not need physics simulation.
you are at the beginning of a long journey
that library is called... a physics engine
you shouldn't really use Task.Run. you can do
async UniTaskVoid SomeMethod() {
...
}
void Start() {
SomeMethod().Forget();
}
if you want to run a task and you don't care what its result is
UniTask has ways to start a task on a background thread or the main thread, and to toggle between them within the task.
but everything in the unity API that has long IO times, like UnityWebRequest, already does work on background threads, so you don't have to worry about it
hey guys
can you give me some help with a easy to medium math problem that I am facing in my game?
mhmm
Imagine the scenario:
You have a world with 15000 cells in it
At water level 50 the amount of land cells is 12214 (81% of the world)
At water level 150 the amount of land cells is 2374 (16% of the world)
How we can deduce from this data what would be the ideal water level for the world to have 30% of it as land?
thanks for the "mhmm"
I guess it has to do with Two Point Slope Form but I am too dumb with math
I just want a deduction given these 2 values
sounds likey ouv'e already figured it out
terrain surface area doesn't decrease linearly with height
usually it's quadratic
oh
This was just a hint that a math friend gave me
But I just need a good guess/deduction, don't want it to be perfect
it is in a random generated map
you need at least one more data point to construct a reasonable interpolating curve
hmmm
i can have it easily
but then how I do the formula?
Which I use/how to implement it?
multiple ways, you can make a guesstimate by drawing a spline through the values (i.e. in a vector drawing app) or do actual polynomial interpolation https://en.wikipedia.org/wiki/Polynomial_interpolation
In numerical analysis, polynomial interpolation is the interpolation of a given data set by the polynomial of lowest possible degree that passes through the points of the dataset.Given a set of n + 1 data points
(
x
0
,
y
...
there are also statistical interpolation methods that may be more helpful if you know the generating function of the terrain
the answer for your two datapoints is approx. 128 btw.
as you can see its not 100 at 0, so you definitely need a curve 😉
I managed to get the Two Point Slope Form functioning
But I need only some estimate, the world is too much random for exactness
you can also use wolfram alpha to calculate that polynomial for you if you give it some more values https://www.wolframalpha.com/input?i=interpolating+polynomial+calculator&assumption={"F"%2C+"InterpolatingPolynomialCalculator"%2C+"data2"}+->"{{0%2C100}%2C{50%2C81}%2C{150%2C16}}"
Hey Can anyone help me with an issue i am having with photon and animation rigging? This is pretty advanced code at least to advanced for me.
I have a local custom package I am making. I need to include another package (YamlDotNet), but it's the kind of package that doesnt have a com.company.package type of URL , it goes directly into the assets folder. How do I make the system know it needs YamlDotNet as well? (If I include it directly in the package, it conflicts with the one I already have in my project.)
Its invisible obviously 😉
I have the full issue in #archived-networking with a video explanation
guys how to update material in Textmeshpro through code ? i've been searched and tried in this link https://forum.unity.com/threads/solved-unable-to-update-material-properties-at-runtime-textmeshprougui.680461/. But it's not worked.
Bullet is a very good option. Although you need to use this in client aswell instead of unity physics (nvidia) for a deterministic result.
Psyonix uses this engine in rocket league
is it in any way possible to load assets without using a Resources folder?
it sucks that LoadAssetAtPath only works in the editor
#📦┃addressables is a form of runtime loading that may be what you mean? You can also do OS-specific stuff as any other application can.
Hey everyone, I followed brackeys Save system on youtube and I managed to make a currency system where my player now saves the coins they have after every run of the endless runner game. The load happens every time the game is launched.
My problem is the following:
I will make the game for ios. The currency will be able to buy skins etc. Do I need to make my player's coins to be saved somewhere online instead of the device? How do I connect it with the app store account in order to be global?
Any suggestion on how to proceed?
You have some kind of access to filesystem on all platforms afaik, so you don't have to, but a lot of these platforms also offer cloud save type of features which you might want to implement.
If you want to let people use ios and android with the same account, you gotta put some server on that stores those files and handshakes with the platform specific game systems (if you want to use them).
You will always have to calculate the world transforms of the parents to get the world transforms of the children. I can't find any references to it, but I'm certain that Unity is caching things behind the scene to only calculate when things have changed.
So calling transform.position on the second to last child and then on the last child shouldn't cause double work
In that case, transform1.TransformPoint(transform2.localPosition) will give you the world position of transform2
I'm interested to hear if that runs faster for you
No, you need the rotation and scale of the parent as well
The rotation and scale of transform2 has no effect on its own world position
are there sensible patterns for not repeating code that does the same thing just for different components of vectors?
like i find myself copypasting blocks of code and changing the Xs to Ys pretty often when doing stuff with vectors ...
you can use a loop, taking advantage of the indexer
for (int i = 0; i < 2; i++) {
myVector[i] = myVector[i] + 1;
}``` for example
oh cool thanks, that should help
man, i should probably like ... just read through the docs in general a bit, to find the obvious features that i don't even know exist
Heyy sorry but yesterday I went to bed
Hey all! Is there anyway to detect a trigger collision with a tree painted on a terrain? Cant figure it out. Thanks!
The tree is a prefab and should have a collider on it, right?
Did you set up the collider on the tree?
yes
// Use this for initialization
void Start()
{
// Grab the island's terrain data
TerrainData theIsland;
theIsland = GameObject.Find("Terrain").GetComponent<Terrain>().terrainData;
// For every tree on the island
foreach (TreeInstance tree in theIsland.treeInstances)
{
// Find its local position scaled by the terrain size (to find the real world position)
Vector3 worldTreePos = Vector3.Scale(tree.position, theIsland.size) + Terrain.activeTerrain.transform.position;
Instantiate(theTree, worldTreePos, Quaternion.identity); // Create a prefab tree on its pos
}
}
this code gets all trees on terrain and spawns a collider, if possible I'd like to isolate one type of tree to spawn a collider on
Wait, you are not even using the paint on terrain to paint the trees?
Oh sorry, misread
Cant you just place a prefab right at the terrain without instantiating a prefab for each tree?
sorry
here's what I want
I want to be able to paint the trees, then at runtime spawn a collider on one type of tree so that the player can interact with that specific tree
however I need trigger colliders
which cannot be painted
if there are 500 trees that need colliders that would be a lot to handplace
And thats why I was asking if you can use a prefab to palce trees with the terrain place tool
im confused I am painting prefabs
And those prefabs have a collider with trigger on it?
correct
This spawns traps
This predicts where to place it
but when it spawns it some times it spawns them on the edge
Hey guys
So I'm trying to do auto-capture
it works for android and ipad
but for some reason, it doesnt work with iphone 8
Hi i've been wondering on how people setup a function callback ;
void actionCall(args, () => {} //CALLBACK? )
Like how do we declare a function that calls a callback like this? I've tried to search on google but i only see Actions not this way of calling back
What do you mean by "like this"
Action for callbacks that don't return a value, Func for callbacks that do
Func
i cannot find the dll files of the game but i see a file ScriptingAssemblies.dll which has a lot of strings of dll files (which i could not find)
delegates
Action and Func are delegate types
Action and Action<T> are something like ```cs
public delegate void Action();
public delegate void Action<in T>(T a);
oh i see thanks!
is there any kind of way to see what the "current script execution order" is during runtime? i guess those values aren't actually retained during actual execution and the reason i'd like to see it probably points to an architectural issue - i know the execution order value each script is set to, but in a few cases the same public method is called from multiple places and they might have different relative timing which could cause issues
Script execution order is only for events that Unity calls
Whatever method you call does not care about it and is called immediately
There's a tab in project settings iirc
but any method that is called ultimately arises out of a call unity did do (at least in my project without custom threading or whatever), i'd like to know that base timing
like if Foo has a public method Bar that is called by N different other MonoBehaviours which could each be in different positions in the order, i'd like to slap a debug statement in Foo.Bar
precisely because the method calls are immediate
and like i said this just smells like an architectural issue but it'd still be helpful if it could be done
Any tips on how to structure Unity scripts? What are the professional "hard rules" in commercial projects?
I work as a backend developer so we have many "hard rules" in our projects like controllers calling only services, repositories etc.
I know trying to replicate MVC in Unity is bad but I'm trying something like below. One GameObject can have several scripts. The scripts are divided like below in case of Player GameObject:
PlayerController- should be the only "entry point" to this GameObject. The only script in this GameObject which has Update() and Start() methods. Handle Input,Events, delegate to other scripts. Should have no "state" except for model and viewPlayerModel- handle "business logic" like HP or how much damage is to be done (no Monobehavior, plain object), no references to Vectors, 3D, etc. No Start/Update methods. Has state.PlayerView- handle references to other Gameobjects needed by this gameobjects. Handle 3D calculation, Vectors. No Start/Update methods. Has state.- Services like
PlayerService,PlayerSoundService- NO state except for configuration. Plain functions, can operate on model/view.
What do you think?
mvc is really not beneficial in unity
what are the other ways of structuring scripts? what else can the scripts be categorised into? so that each script doesn't become a pile of spaghetti mess :P
The main separation of that style that's worth doing in Unity is to separate your game state into a nice manipulable, and ideally serializable data structure that you can use for saving/loading game state, networking, etc.
follow SOLID, but work with composition rather than inheritance
What about things like input? For example when I move the mouse, and try to find which script did something. Without dividing into e.g. "controllers" I'd need to look into each scripts, since any of them can have "Update()" method and potentially create some side effects when Input is changing.
I'm curious what's the best practice in professional projects, where I imagine there can be hundreds of scripts/gameobjects.
have the input necessary for that component in that component itself
So I imagine they must have some rules in professional projects.
then you also won't have side effects
I'm not convinced 😃 what if you have several scripts attached to 1 gameobject? In that case 1 script updates the movement based on input, and other script can also update movement based on some other condition. So it's difficult then to find out what updates based on what. Unless we make a rule that only 1 script updates the movement (so like PlayerView above but called PlayerMovement). Or unless we try to use 1 script for 1 gameobject? But not sure if that makes sense.
you are not following SOLID then. most important thing: SINGLE responsibility principle
I believe my initial question was about that. So in case of Input, why not make a script called a controller which handles all input? Then it can delegate to a “dumb” script called “movement” which only moves the player. Feels a bit cleaner/more SOLID to me to have that separation…
I can say with confidence that having individual scripts that handle individual player functions saves 5000 headaches later. As an example, this is what is on the player controller for The Callisto:
no, because then you are checking for everything non concerning and delegating it to all kinds of different scripts. i guess it would be a OOP solid approach, but not a unity solid approach
The modularity of these scripts makes them incredibly manageable.
the most important thing you want is to have self contained 'plugins'
the only rule in professional projects is "get stuff done asap so the manager can check a box". There is a lot of theory what professional projects should be like, but they never are like that. Most of code is written with way too little time to do anything but the bare minimum that keeps the boat a float.
anyone know the solution
as they say, there is never enough time to do something right, but there is plenty of time to do it again later.
So in this case, does each of those scripts store its own state, events and input? Is there a “main” script where e. g. Player HP is stored? Or would that be a separate “Player Damage” script?
Also thank you all for input, very helpful
Separate script
Hey anyone here familiar with photon (PUN)? I want to have some data that isn't specifically belonging to any player (public to everyone) and should be modifiable by every player's behaviour. What tool / function / interface should I look into?
Rpc?
[SerializeField] private C_InventoryItem currentItem = null;
this is for some reason not null
it's just an empty C_InventoryItem object
how can I make it null from the start?
because I want to check
if(currentItem == null) {
and its always false, because it's never null
Each of those scripts has its own states and events and communicates through a controller. This allows for modular expansion (plugins) on the controller behavior.
If that's a POCO (not a UnityEngine.Object) then it cannot be null because it's serialized. Unity's serialization system doesn't support nulls
You could make it not be serialized - that'd be one option
another option is to give it a bool isInitialized field and use that instead of a null check
Soo it’s due to the serializeable field? Interesting
Makes sense
Thanks a lot
this should not be serialized
Update is the problem
input system and event system let you author input-related stuff without Update
in my experience, projects that have multiple developers simultaneously touching input code, for example, cease to exist
Can I send an RPC to an object that I do not own?
The logic of my code is as followed:
- The first player entering the room will create an object, attached with a Photon view.
- There's an RPC method that can be used to change the value of an attribute A
- This attribute A is streamed with OnPhotonSerializeView
- The other players joining the room will first fetch this object. Then if they want to make change to the value A, they call the RPC method, basically sending a request to the owner of the object to make this change to A
So right now what I'm getting is:
- The owner of this object can change A, and the result will be broadcast to the other players
- The other players' requests to modify A are ignored. There's no error message so I don't know where I should look into
what is your objective?
are you working from a pre-existing sample?
No I'm doing it from scratch
What I want to do here is to have a public piece of data that every player can modify
Something that logically shouldn't have an owner
make their pieces separate and merge it into a unified view
you should work from a pre-existing sample if you want to be set up for success
photon has great samples and docs
what is the piece of data?
there's no such thing as an X with multiple owners.
Really could use some help with this
it's a beginner code question
Do you mean that it’s because every dev has a different approach? And there is no “hard rule” on how to do things? Or what
it's like a logic puzzle. the kind of developer who could structure input handling code for multiple people to edit would not need multiple people to work on it
InputSystem and EventSystem is input problem solving for teams of 1+ people
Input is for teams of exactly 1 people. if you are using Update to do stuff, in my experience, only the original author can modify that Update
why does Update exist? because it's how flash worked. "Update was a mistake"
Hello everyone, I always struggle to find naming conventions / variable names convention / GameObject "constructor" conventions, you know...
Are there any books or official documents or whatever?
i can share my .editorconfig file lol
Unity's naming scheme isn't 100% plain old editorconfig compatible
i use Rider
I can't afford :/
once you discover UniRx & UniTask you interact with the Unity callback system less, you make stuff that's easier to use from other scripts and a better kind of abstraction
then the structure of the scripts matter less
public void GetLargeText(string url, Action<Exception, string> OnComplete) {
try {
var text = PrivateGetLargeText(url);
OnComplete(null, text);
} catch (Exception ex) {
OnComplete(ex, null);
}
}
GetLargeText("http....", (error, text) => {
if (error!=null) {Debug.Log("There was an error."); return; }
Debug.Log(text);
});
Thanks, it’s the first time I hear of those.
it's like DOTS but in shipping games
a and c must be set by the instantiator, how do you make it explicit?
public class Player : MonoBehaviour
{
public a;
public b;
public c;
}
Make a constructor that take these two values
I did something similar, but I haven't seen someone doing this before
Before proceeding, your class doesn't derive from MonoBehaviour right?
Oh, sorry, I fogot to add the MonoBehaviour xD
Fixed.
I created a function called "Constructor" that by convention would be called after the Instantiate, but I haven't seen anybody doing this
Unless that class only stores data, and is not meant to be directly attached to a GameObject, and receive Unity messages such as Update
If you need it to be attached to a GameObject, then you can throw exceptions or log errors in that script's Start method
Like this
void Start() {
Debug.Assert(a != null);
Debug.Assert(b == 0);
}
Hmmm interesting, I could create a flag to know if the instantiator remembered to call the constructor
And I also can check if the instantiator called the constructor twice and so on
What do you think?
It seems like a good alternative to constructors yeah, especially when they're blocked like that
void Start()
{
Debug.Assert(isInitialized);
}
And in the "constructor", Debug.Assert(!isInitialized) to have an error if you call it multiple times
Yes! Perfect!
I think I will call it "Init"
Thanks for the help @fresh salmon !
UNITY_ASSERTIONS must be set in your scripting defines for this to work i think
Is there a reason Awake doesn't work for this purpose?
Ah, missed the note about the "instantiation"
Don't mind me
Is it possible to change the shader of only 1 object during runtime?
I want to create a "collision" effect that where I only want the closest object to light up by changing the shader.
yes it is
Photon doesn't sync movement when there's no movement detected, is that how it works?
Care to elaborate? Changing the shader affects all materials
So the thing is, I have an objct with a Photon Transform View Classic attached
And the object has some movement that starts as soon as it's initiated
@arctic robin check out MaterialPropertyBlocks
And this movement cannot be perfectly synced to the other clients - on other clients' screen, this movement is only partially done
I wonder why
I'm on it
👍
@arctic robin as an addendum, if you use materialpropertyblocks in certain ways (read: everyday use cases) it won't result in any extra draw calls either
I fine it pretty advanced kind of that's why I posted it here
usually the "advanced" is interpreted in roughly absolute terms rather than relative
That worked wonders, thanks!
yay
Furthermore, whats the recommended way of "hiding" a gameobject without disabling it?
move it really far away
It's not in the UI, is it? If it is, CanvasGroup is a lifesaver. Lol actually maybe there'd be some weird workaround where you could enable a Canvas and a CanvasGroup on your parent object, with the CanvasGroup alpha to 0f, when you want to hide, then disable both those components when you want to reveal again
Hahah I'll look into that
Also is it possible to set the anchorpoint of a cube?
do you mean the origin of a unity cube?
Right on. I have a rectangular cube that I'd like to fill with cubes 1/4th it's volume each step.
Going left to right
you cannot change the origin of the default unity cube
code
That's where I'm at. Just wondering if you had more pointers or perhaps any standard objects thatd do the job
if you get the bounds, then a placement step would be bounds / 4
in order to offset their position (assuming you want to child the smaller cubes to the bigger cubes), you need to subtract 1/2 the cube's size from your positioning
Haven't worked with bounds before, what do you mean by that?
Atm Im cavemanning it like this
with the unity default cube that works, bc the cube has a size of 1
but if you want to get the real bounds you can grab the renderer or mesh bounds
off the MeshRenderer or MeshFilter
Interesting
(mesh bounds is local to the mesh, renderer bounds is an world space AABB)
Cool, looking at it now.
Also, AABB?
Axis Aligned Bounding Box
basically means that all the axes of the box always align with the world's x, y, & z axes
even if the mesh is rotated
Haha cool
Is min and max arbitrarily positioned?
Furthermore, I got the scale down thanks to your bounds suggestion, now the question is just the position.
if you look closely, you'll see that min and max are positioned so that they are perfectly touching the outermost points of the collider at every moment
How does that work in a 3D environment?
same idea, but with a third dimension
<- when on a cube would it be bottom left and top right and vice versa?
it would be the smallest unrotated rectangular prism possible that completely contains the cube
Interesting
Am I thinking about this correctly?
Size of block spawned is all well and good
Seems the object moves on the z axis, and incorrectly for that matter.
Bounds bounds = GetComponent<MeshRenderer>().bounds;
Vector3 objectScale = new Vector3(bounds.size.x/4, bounds.size.y, bounds.size.z);
objectScale.Scale(new Vector3(0.93f, 0.93f, 0.93f));
GameObject blockman = Instantiate(seqBlockPiece, transform.position, transform.rotation);
blockman.transform.localScale = objectScale;
blockman.GetComponent<Renderer>().material = renderer.material;
blockman.transform.parent = this.transform;
// Move correctly
Bounds blockBounds = blockman.GetComponent<MeshRenderer>().bounds;
Vector3 newPos = new Vector3(bounds.size.x / 2 + blockBounds.size.x / 2,
blockman.transform.position.y,
blockman.transform.position.z);
blockman.transform.localPosition = newPos;
Ugly code, will be cleaned up
Yeah I'm stuck lol
These are the box's reported bounds?
Trying swapping between local and world space bounds but the spawned cube's bounds are equal to that of the box it spawns in.
Is the way a scene is serialised deterministic? Or does new stuff get added to the end?
I'm creating a bunch of new gameobjects at runtime and i would like to serialize them so it doesn't have to go through the steps everytime you launch the game, how would i do that ?
@full flax Don't cross-post.
sorry
Perhaps somebody here knows something about the problem I have:
Sometimes, one of my asynchronous methods running in the background are not informed of a cancellation token cancelling.
These tokens are cancelled, but IsCancellationRequested does not appear to be true.
Is it possible that the reference to the token source is somehow lost?
The weird thing about this is that the WaitHandle of this token does get a notification when the token is cancelled.
So right now I use https://hatebin.com/kjgyqahbed, but I want to use https://hatebin.com/uwbbjapiek because this is a proper implementation that implements INotifyCompletion and ICriticalNotifyCompletion. The latter sometimes does not work, however. The method that uses this is https://www.toptal.com/developers/hastebin/ikuyepalux.csharp. Line 20 gets the task, line 24 awaits it, and line 30 should be logged when cancelled. This does not always happen, however, even if any of the other task complete and the loop restarts.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
So I wonder: why does this task using a wait handler work, but an implementation of INotifyCompletion and ICriticalNotifyCompletion does not? Because if I replace line 20, var cancellationTokenTask = cancellationToken.AsTask(); to var cancellationTokenTask = cancellationToken.AwaitCancellationAsync();, everything works fine.
I would like to mention that if I create a test project that uses the version with INotifyCompletion and ICriticalNotifyCompletion, it works fine (this is the test: https://www.toptal.com/developers/hastebin/zufatixeso.csharp)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I have some custom packages. Core, Utility and some modules
Core package depends on Utility package and module packages depend on Core package.
How can I figure it out and resolve the dependencies?
A project can use some modules, for example Module1 and Module2.
Core => Utility
Module 1 => Core
Module 2 => Core
...
Do scenes have any advantages over prefabs that I'm not aware of? To me, prefabs are superior in every way. Instantiating a prefab to get tye scene's content feels way simpler that loading a whole scene. It simplifies the management of singletons, because I don't have to dontdestroyonload and kill off new instances, or any other nonsense. And I can still have a test scene where I'd set things up. What am I missing?
define "resolve"
you can't have prefabs without scenes
I'd set them up in test scenes, but load into the game as addressables
for better singleton behaviour, look at scriptable objects
I know what those are
you still need a scene though. ???
how do they solve the problem
I'll have only one scene that will load stuff accordingly
and more test scenes for setting up the individual prefabs
That will only exist in the editor
why are you writing this in code-advanced? it has nothing to do with code, and certainly is not advanced
Hello, I have a few questions about how memory gets allocated when creating variables of type interface in C#:
- Does creating a variable of type interface in a function allocate the memory of that variable on a heap or on the stack if it was assigned as a struct?
- If you create an array with generic type interface and populate the array with structs. Are those structs allocated as objects just like classes on the heap and the array simply becomes an array of pointers to those objects?
Code example - https://www.toptal.com/developers/hastebin/boperowako.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
structs get boxed, that is, a copy is create on the heap, as long as it's used as an interface
actually, all structs internally have their reference version. it derives from object and has all the usual crap that classes have (like type info, virtual method table)
Hello there 👋
- yes
each one individually
if you want to avoid that, use generics
structs can imlement i terfaces mainly for their use in generics
I'm trying to achive a pretty complex input system (with the New Input)
the player controller is a TP and with AWSD I can control the character as usual, what I would like to achive is to play "dodge" animation on double-tap on AWSD too
dodge/roll ... you know what I mean.
Sorry, ok thank you 😄
Thanks.
Hey everyone, I'm not sure where is best to ask this question but how "taxing" are counters using deltaTime on the game? I.E "could" the game run 100s/100,000s of these counters at the same time without any degradation - of course there are lots of other factors to consider, but for an example assume pong if you need to
not that taxing
the calling of thousands of Update functions on its own is worse than the actual use of deltaTime and adding the numbers
And to get a real answer for your question - try it and see. Use the profiler
My goal is trying to determine how far along a path the "enemy" is - there are potentially 100s of enemies in the game, which all have their own counters for debuffs blah blah (as you'd expect within a game), I can't think of the logic needed to determine the distance between start>finish when the path can wind back on itself
how is the path defined
There's a winding path which counts from 0 = start > # = finish
and not sure how a deltaTime counter is relevant to that really
0 = start > # = finish I don't understand this notation
It's not, but I can't think of how to determine the "closest to the end" enemy
So, there will be 10+ "waypoints" that the enemy will follow
the enemy which has the least remaining distance to travel
Distance will vary depending on the level and waypoints that are set
are you using navmesh?
for each enemy and each remaining waypoint it has to travel to - you add the distance from the enemy or the previous waypoint to that waypoint
the sum of those distances is the remaining distance
Navmesh is new to me, I'm not using it at all
The issue I have is that the attack point will differ, so the path isn't always obvious(at least to me)
this might be handy about waypoints, distance left on paths and what not. But just a suggestion to look into and evaluate. If you already got a working waypoint system, I'd go for praetorblues approach
wdym?
If you don't know the path then obviously you can't compute the remaining distance
I don't know what an attack point is
but you said you had waypoints
I'm getting confused between both of your questions but it's a tower defense game which has a winding path - I am literally thinking of adding a timer to each enemy so that when I know it's on "waypoint6" I will use the timer of each enemy to determine who is "closest to the end" - however, this timer is useless for any enemy that isn't the closest to the end and if there are 1000's of enemies, it's a useless timer; but I'm sure there's better ways of achieving what I want anyway
i don't see what a timer would do for you
unless you just mean to calculate the age of the enemy
You want the remaining distance of your object on his current path? Clear said?
Tower assumes highest counter = closest to "end" ; I use the waypoint # to determine which group of enemies I should pick between
I'll get a screenshot example of what I'm on about
So you want the tower to always attack the enemy with the farthest progress on path?
Correct
And they change depending on movement speed, slowing towers and what not
But the path can interwine so the towers will select what is closest/further from it - but not tell which is closest to the "finish" zone
So the enemy with most progress and within range of tower
Okay, got it. So you got the range of the path, because you can just add up the distances from waypoint to waypoint, right?
Ahhhhhhh right, that makes so much sense - I guess I was hoping for a more intuitive way of doing it
And same goes for your player
I just need to calculate the distance between x-y then work out where the enemy 'is' on that path
Just register the enemies with the waypoint and pass the waypoints 'progress' on the whole path to the player + the players distance from the last waypoint. That should give you the total percentage on the path
In that case you get dynamic progress if your enemies get knocked back for example
So enemy hit waypoint 1, use waypoints progress on whole path plus enemy to waypoint distance, which could also be negative until you reach next waypoint
Ah okay, that's why I was thinking of adding a counter - I know which waypoint the enemy is 'walking' on, so I was just going to use the 'highest' number from "enemy#" and then make the tower attack that. So, on the pic, the towers are placed on the white squares and enemies will walk along the grey path.
Do the enemies have colliders on it?
Funny you say this, I do have things that make enemies run backwards, but I'm happy to write the code to reduce the counter when that happens
Yeah, I use that to detect when the enemy is shot
So you can use spherecast from your tower to get all enemies inside range and then just iterate through their progress to attack the right one
"Age" was my initial thought, since it would be a counter that starts when an enemy is spawned. I have the ability for enemies to spawn "duplicates", so I'm happy to duplicate the timer on the new enemy, but that's the line of thought that I had initially
And again, progressOnPath from your enemy can always be currentWayPoint.progress + DistanceTo(currentWayPoint) / wholePathLength
the only issue with that is that a younger enemy might still be closest to the end if they move faster than another one. Also there could be things like "slowing" towers that change things too
depends how much you care about those nuances
but age might be a good starting point that you can improve on later
I would not go with a timer/age counter tbh, thats why I would register for the positions
(I've thought about these tower defense things a lot 😆 )
This is my current code for near/far enemy - it just doesn't "do" closest to "endzone" http://pastie.org/p/4OWFLWJVLuoYquQDi6tnqc
Exactly lol, I need to capture this as well
Did you get what I was trying to say about the path progress? That would actually do exactly that 😄
Yeah there's all kinds of metrics you could theoretically use for tower targeting. You might want some towers to do it differently than others too
ideally you would do something like timeToDestination = remainingPathDistance / speed for each enemy. And use something like what twentacle is talking about to calculate remainingPathDistance
then you pick the enemy with the smallest timeToDestination
Here's my full tower script but I'm trying to digest what you've said and I'll reply to that now lol - http://pastie.org/p/6X4rYgmcqxtIsExhhJnY9U
Just curious why you even need the timeToDestination. I think I am missing something from your guys thoughts
You're not (probably) it was my basic brain wanting to use a counter to do all of this work (but given speed differences, I knew it wouldn't work from the get-go)
Oh okay. Yeah, just get the right now path progress and that should work. So you always got the realtime position and your towers can handle it better instead of assuming who might be furthest 🙂
because faster enemies can move further in less time
so they may be the more dangerous ones to worry about sooner
it depends how smart you want your towers to be
Ahhh, got it. Okay, types of enemies is next step then, got it 🙂
I also never seen an enemytype that ages over time and dies if not reaching the end, would be a cool addon, sorry, brainstorm mind active 😄
again you could use all kinds of metrics in this calculation and mix and match:
- distance to end
- time to end
- age of enemy
- hp of enemy
- distance from tower
- some kind of weighted combination of all of the above
You did put some time in those thoughts obviously 😉
you could even have upgrades for towers that switch it from a dumb metric like "distance from tower" to something smarter like "distance to end"
Haha, I'm being a complete pain in the arse and allowing the players to potentially specify whether they want the towers to attack closest/furthest/[x] enemies
yeah I've thought a lot about this over the years lol
yeah so in this case you'll need to define all of these functions and allow the tower to switch between then 😛
Like a code the towers game, that would be cool. Where you can stitch together mechanics the towers react to... okay, gotta get some paperwork going for patents 😄
I used to play a crapton of tower defense games back in the Starcraft Brood War custom games scene.
There's so much nuance in there that people don't realize
Yep, good old SC times
This is exactly my thought, I'm able to achieve most of those because once the tower knows what enemies are in range, I can tell it "highest HP" - I just wasn't able to work out the mechanics to differ between the speed on enemies along the path that I have set
Yup! This is why TowerDefense is my first game to develop as I think these mechanics are more "nuanced" than general FPS/other games that I would play - plus I can easily tweak tower attacks/defences blah blah and not worry about playerguns etc..
timeToDistance (is the calculation of the distance between waypoint6 > waypoint7) = remainingPathDistance (calculations between start>finish of waypoint) / speed (whatever the enemy speed is) ?
I was thinking more calculating the total distance to the target (the player's nexus or whatever) not just to the next waypoint
Not sure if that's what you mean
Ahhh, so you were thinking of calculating the full length path of the enemy - so Waypoint 0 > waypoint [x]?
yea
it can be largely cached too - especially if the path is known beforehand and all the enemies follow the same path
you can just calculate that once at the beginning and reuse it constantly
and the enemies can just take totalPathDistance - distanceTraveled to get the remaining distance
Then you just keep track of distanceTraveled which is pretty easy to do
That makes so much sense! So just to specify it, I can calculate in the Start() what the total distance is and assign a travelID to the enemies. For my duplicates/summons (mid-path), I can just duplicate the current travelID and it will then adjust itself based on 'its own' speed and towers will know whether its faster>closest to the finish-line
Stupid question time; totalPathDistance = 1>100 (for numeral sake), how do I make sure distanceTraveled is calculated based on the speed of the enemy? I assume using timeDeltatime will just produce the same number for every enemy, I'm struggling to see how I make "distanceTravelled" differ depending on the units speed
you wouldn't. Distance traveled is just part of the calculation for distance remaining
distanceRemaining = totalPathDistance - distanceTraveled
Then the part that concerns speed is:
timeToDestination = distanceRemaining / speed
speed only matters if you're worrying about which enemy will reach the target in the shortest time
if you just want to do which enemy is closest to the target / farthest along the path then you don't worry about it
Good point, the tower just literally wants to know what to shoot at, when an enemy leaves it's range it 'should' disregard that as a target - for towers that have consistent attack, it will just disregard the out-of-range enemy and move onto the in-range enemy. I'm just trying to translate what you said into my brain-language atm (I have started drinking :/ my bad! )
I'm not trying to intervene with "just because enemy speed is 15, shoot at that one because the other enemy is speed 5" - I am literally trying to determine which is closest to the "finish-zone"
You need to do that via mapping. Otherwise nearest in the world of geomtry isn't the nearest in terms of tile pathing
But yeah as shown above is the right approach
oh you are still here with your issue 😄 let me read up 🙂
How are you moving the enemy? with transform.position?
Could someone explain to me how Photon works in a general sense?
I'm quite confused when writing Photon code. It feels like each player gets a copy of the synced data, but there's also the concept of a master client, and the setup isn't serverless... So it's kind of like P2P, but it's not
It's like there is a server required to do some work (matchmaking and passing around data), but you cannot really write server code or store any custom data on the server

It's not making a lot of sense to me
you are separating code with client and rpc flags, with this, you can do your server and client stuff and store different things, call different functions. At least from my last knowledge some time ago
Is it still possible to emulate different network connection types in Unity? There used to be a feature that allowed you to do that in 2018 or something.
I mean, I could open a bunch of browser tabs. But ideally, there's a built in feature...
Hello! any idea how i can make this work?
Try passing int[,] in the type argument?
Or nothing at all, it can infer the type from the argument
I managed to make it work like this, maybe this is how it is used
I cannot seem to find any docs for that method, but from your code its signature is
static T[] GetSubArray<T>(T[] array, ...)
So it may not be what you need, what do you want to do with that array?
Ah, so like a 2D slice of it, here the 4 values of the "bottom right square" of the initial array
in this case it is in the corner, but in the real case it can be anywhere in a larger array
dude just use loops
You need loops yeah
this is not python
but the loops are not going to slow down the code?
AFAIK there is no n-dimensional slice of a n-dimensional array method implementation in C#, and if it ever exists, it uses loops internally
ok, then I'll use loops, thanks to everyone!
Hey everyone. Loaded question time. I have been tasked to see if there is any current networking solution that could
be used to allow authoritative cross-server gameObjects. i.e. could be used to "stitch" scenes together client side
(one per server) and allow players to traverse between server scenes and interact across them without the player ever
realizing and doing so avoiding "zones"/cutscenes. Open world style similar to WoW and others. I have looked at Mirror
and while it is a very reliable multiplayer codebase, there is no method for one server to relay gameObject updates to
another or to "hand off" control of an instantiated gameObject. From what I have been told by a few people, they do not
think it would be possible to add this feature without at least a few people of very high skill level and an
extremely large time frame. Any direction or thoughts are greatly appreciated. Thanks (I am open to DMs if you feel it necessary)
yeah that's very complicated
It sounds like a small 'addon' but it is quite a feat since it has to be reliable and not stutter/effect gameplay actions.
yeah it's not small
you're getting into deep MMO design
For better or worse, but my upcoming book “Development and Deployment of Multiplayer Online Games (from social games to MMOFPS, with stock exchanges in between)” is on Kickstarter now… “Beta” of the book (available on this very site) has been praised by quite a few senior developers from the industry (from Amaya to Zynga, with quite …
you need to architect your entire game around this ability
managing stuff across different servers is a massive headache
and carried a lot of deep implications
That is slightly different. Here we are just looking for server to server hand off of authoritative game objects without the destruction of the original object or a loss, lag or duplication of player input.
what is slightly different
you're not just talking about hand off, you're talking about a seamless transition between servers
that goes both ways
is this only for players? what if someone shoots something across a boundary?
what if someone bounces between the seam quickly?
yes, this was described as any object but also player objects need reliable input. regular game object traversal between servers is actually fairly easy in mirror as you can create, destroy server side and represent client side without it actually destructing. the player object and its input is the biggest concern.
as for bouncing between, there would need to be a 'boundary' zone along the "seams" to indicate where data sharing starts, and a point of client changeover along with a fast-bounce protection that if a player is quickly moving back and forth it will only make the first official handoff and create a delay until the next unless the client reaches a furthest point from the seam itself.
how does the client communicate to the server?
is there a central hub, or is it talking directly to the server its currently in
in this case each 'area'/scene is hosted by its own server. as normal the client connects to the server it would be on, as it gets close to the 'seam' that the server is aware of and connected to, it would tell the client to additionally connect to that server to start receiving updates and be ready for a possible switchover.
This is a thinking kind of based on how Mirror currently works and would need to be adapted.
I feel like you would need a hub anyway
But that is why I am looking if anyone has better suggestions or alternatives
What would the purpose of the hub be exactly?
orchestrating connections between servers?
I don't have any alternative suggestions, that seems about like how you'd have to do it
how would that solve the problem of not destroying the players gameobject on the server (and subsequently the client) when traversing between servers?
That being on of them yes. Transferring a player to other servers too, two area servers directly communicating between themselves feels wrong without anyone else knowing whats happening.
but the data would not be relevant to any other service or server for any reason. (?)
Game state..?
@jagged notch I don't know what networking solution you're using, but you'd need to have the transmitted objects know that they have two "parents", so that they only get destroyed if they have no parents left
Mad: Was using Mirror as an example. with an authoritative server setup, the server networkInstiates the playerObject (or any network updated object) this creates it on any connected client as well as tells newly connected clients of these obejcts and to create them/update them.
The server then does all the trusted collision checks etc for code safty reasons etc. if the object is destroyed, the client also destroys the object. (and all other connected clients)
Thusly, a "plugin" for Mirror that would override some of this, such as the destruction of the clients copy of the gameobject and changing the servers copy of the gameobject from being the 'master' to a regular game object (and vice versa on the 2nd server) would be a solution. This prevents the client and other clients from having the specified playerObject destroyed, and the client could make a quiet switch between authoritative servers
Writing a whole networking solution from the ground up is not an option for obvious reasons. Which is why I am hoping for ideas other than the current one to make use of existing technology somehow since I have not been able to find anyone with the expertise to make the necessary changes to Mirror. 🙂
mm afraid I can't help you there. I am good for philosophical discussions of networking but I don't know the breadth of tools available 😄
I greatly appreciate it either way 🙂 Thanks though!
Guys, who can check and give feedback on code architecture ?
I dunno if anyone wants to trawl through a code base
but if you have a specific architecture question you may ask it here
it's a space shooter. and I don't have any specific q about architecture.
I will wait
Thanks
To simulate pedestrian movement (random) in city/town building games, the common way is to use flow field with random noise (perline noise)?
that is one way
Usually they are not completely random, right? They are painted?
flow fields
SpatialOS is all about that. Not cheap, not easy, enterprise level solution. https://ims.improbable.io/products/spatialos
Thanks. Like you said, it is quite expensive and only goes up. It also requires using their servers as a hosted solution. They have also since increased their prices and it would be unwise to develop a project around a company/business that can literally hold your project hostage for more money when they deem fit. So it really does not fit this need. (You might notice that recently they have hidden and removed any references to pricing)
Also, things like Unity's fight a few years ago with Spatial is another example of reasons to not want a project wholly reliant on such a setup.
When it comes down to business, it only matters what you can afford, and finding people who can build a MMO at that scale is almost impossible. So it might be the only option.
most good gamedevs have been hired by one large company or another to protect themselves from competition
Agreed. Thankfully this is not a full MMO and we are just looking to solve a particular solution. Granted it takes keeping a lot of things in mind and having a good understanding of both unity and networking.
start with a photon sample that's closest to what you want
it is a mature multiplayer platform
I have not found a similar solution with photon either
can you give a logline of what your game is? @jagged notch
this is abstract. what is the game?
This is a multi-use case. just need to achieve basic concept of allowing objects to move between scenes/servers seamlessly
the initial case use would be for a space based game
can you be more specific
as for the network requirements?
like what the game is
sci-fi fps/space battles
cool
have you/your peeps operated another multiplayer game before?
it's okay if the answer is no
a small round based game similar to among us
how did you do the backend for that?
visually? or network?
network - like did you use photon? gamespark? playfab? did you operate servers on EC2?
was it peer to peer?
Mirror
no, the dns was hard set. It was hosted on our servers
I ran the servers in headless mode
you started an EC2 instance?
no, we have our own servers
yes, we have several racks and a few 10Gbe uplinks @ at datacenter
No. Debian
actual metal, not vps deployed
okay, and which of the following would describe your peak concurrents
1-10
10-100
100-1,000
1,000-10,000
10,000+
okay
got it
my feeling is, there is nothing essential to your logline in terms of "seamlessness"
you should use photon
a. dont want to pay for others servers when we own our own already
b. we have not seen any examples of photon being used for traversing between scenes
without the use of some sort of "zone" / "loading screen"
the game would appear to the players as a large contigious space, leaving from a station, into a ship, into atmosphere, onto planetoids
you could make a nice illusion that would work for space specifically
but could you actively fight across said illusion?
usually the seams are limited by number of concurrent players present, not literal transformational scale/ game content
thats more of a unity problem than a photon problem
unity cant do "huge worlds" without loading screens
which is the point of multiple servers to spread it out
and load each area sectionally
has nothing to do with compute performance
unity just cant do it because of its architecture
going from 1,000 concurrents to 10,000 is like going from rank 4,754 on steam to rank 822... it's very hard
not worried about the concurrents, those can be limited to 100~200 per server
the issue is crossing the space
anyway, to keep it grounded in reality
"huge" means lots of assets and objects, not huge is physical size
if i were you
if this was not an authoritative system it would be fine
i would start with a specific photon sample that does what i want to do engineering wise
and create fun within those limitations
there is no point in making an fps if you want to make an MMO, and photon has no mmo sample
so the whole goal would be a seemingly contigious space game
where you could fps/ship fight at any location without getting stopped by location limitations
one interpretation is that photon is technically lacking. another interpretation is that there isn't an audience for MMOs...
that is what i have said
however making an mmo with server-phasing or whatever you call it is out of scope of even well funded and experienced teams
i'd say its the audience, or rather the reality of it
world of warcraft lacks seamless instance traversal right?
yes
it does it all the time
original wow that is
you can move/fly from one location to another many many many zones away, fight or do anything along the way
I have been playing mmo's since original EQ came out
can you list them?
even original wow 16~ years ago supported this
it's promising that you as a human being try new MMOs 🙂
in wow you never leave the server though
but on the flip side, the bulk of the audience for these things is, you are playing the same MMO forever, by definition
the "server" is a name for a "shard" of players
there are many many many servers that make up wow seperated by zones
trying to stay grounded in an executable reality here
any specific zone can go down where you simply can not cross into them
your best bet is photon
original wow had nothing even close to server-sharding
can i ask how you orchestrate your own servers?
which offers nothing like this
and how do you do observability for them?
depends on the need. kuber sometimes
so your game backend, it existed as a container?
everything is setup based on use case
does anyone know how you could store numbers that are 2^1024 or larger? my only idea atm that i dont really like is to store it as a string in a struct/class
did you define a StatefulSet for your game backend, the one you've operated?
or was that deployed differently?
the kub cluster was managed seperated from unity. we tracked usages and loads and as needed we spun up new systems
okay
not that you would ever put anything like that directly in unity
hmm
that is a network/server managemment system
photon is your best option here
Thank you I didnt realize something like this existed
btw, i get your concern, I am not john doe avg windows user wanting to make a game. 😉
the person funding all of this is not going to give more money* because of a "better" networking decision
While my specialty is networking for the past 16~ years, I am still lower intermediate with unity, but I am not doing the actual game programming. that is for the team
they care*, but they care more about graphics
graphics are great, but the the core game engine/system must be stable, reliable and reasonably efficient
if your team wants to develop an MMO, focus on a sick demo, just like No Man's Sky did, which did everything you're describing for the most part
do the demo in unreal. after all, while unreal won't help you make something that isn't an FPS, it will help you get something financed
everything else we're talking about... your servers are going to be obsolete by the time you use them
because the development cycle on something like this is so long
and the marketing budget to build this kind of audience would be huge
you can easily, seamlessly move between large transforms in unity
you cant proove anything about an mmo that doesnt exist
for 1 player
there are no unsurmountable obstacles
build the scene
for 2 players it will still work well
yes, but the point is to make a proof of concept to show that it is possible to make a "game space" that spans multiple servers without loading in/out or hindering gameplay
i develop a unity streaming technology. in my framework, you make a local multiplayer game and stream the cameras to each player
how would you even proove that without actually building it an testing it with 100s of CCU
receive their inputs, and it works really well. but that obviates the need of a networking engineer
doing what you do well involves eliminating your job description. do you see?
the best proof that its possible is another project that has already done it
load testing can be done with X test clients running and random input
dont need 100's
just need 20~30 even
i'd not buy that as a proof of concept
so if you want to make an innovative new game, my approach is going to be 1,000x better than writing a networked game
because the problem IS the networking.
if you lose all enthusiasm for this by eliminating the networking blah blah, don't do it
That is all fine, but I am to attempt to find a solution matching this goal and say with confidence "there are no alternatives and it is simply an impossible task" or "here is an option of how to do what is requested".
one option is to use a networked streaming solution, like Stadia except publicly available and multiplayer
that would make your task possible
then your team is developing a local multiplayer game, from its point of view, and can use extremely powerful machines that are unconstrained in terms of content & scale
please explain how using said network streaming solutions solves the current limitation in unity of maintaining authoratative collsions etc for a playerobject (or any object) across multiple servers so I can better understand.
you wouldn't need multiple servers. there's no networking
your end user receives audiovideo, and sends inputs, like stadia / geforce now / xcloud
so in the case of 9000 CCU, and a a large amount of unity scenes ...
it would be a challenge, but the path is clear for this approach
it still does not solve the issue of it being hosted on our servers
and not have any dependency on third parties
okay, suppose you can host it on your own servers
yes, so back to the current goal of looking for a method of handing off authoritative control of gameobjects between servers.\
you can run this software on your own servers, if you choose
why not? it's software, it runs on computers. why not use your computers.
can you point me to such software?
i DM'd you a demo
Thank you, i feel quite closed minded because I am not understanding how this relates to the networking needs
it's okay
now imagine what you just saw, except two people connect to the same unity instance
your unity game you engineer as a local multiplayer game, with input system local multiplayer.
however many people you want really
you can run the unity game, the CLIENT, on a very powerful computer
i mean, the load for a single instance would become insane
what does the 1080p... .. you mean the whole thing is streamed??? video?
and now poof. you don't have to constrain yourself in terms of gameplay you can do networked
i see you didn't realize that wasn't webgl lol
i mean.. that is waaay outside of the needs of this.
ppl can install and run the software fine
i'm trying to solve hte problem for you
and there you go, you saw it
you can run many concurrents, and they share a world seamlessly, and you are less constrained because the game can run on an extremely powerful computer
some server is hosting the unity instance.. at some point, it has a memory and cpu restriction
and you don't have to write a line of networking code
you build servers, so you know those limits are pretty high
even the craziest multi-socket servers cost less than 1 year of an engineer's time
anyway, just think about it
you asked for the solution
you saw it, it wasn't vaporware
sounds like an interesting alternative that I can present as another option
good, good 🙂
see i was helpful
especially for a proof of concept
which might just need a few players sharing this big world
essentially you have proposed the same as stadia but suggessting they host both the server and client instances(?) even just the server instance.
stadia is great. you wouldn't have a server per se
the server and the client are the same process
just like a local multiplayer game
stadia can't do this, yet, not for a few years, because it's virtual desktops
alright, that option aside, I still need to continue to look for a solution fitting the request.
its basically a mainframe with terminals
To be able to use headless instances of unity servers to perform authoritative control over gameobjects that can be passed between them without gamepley interruption.
improbable has been trying to do that for a while
they reinvented DOTS, which is reinventing cap'n'proto
and trying to use Unity as just a rendering engine, which it's not that good at anyway
so think about it.
you can try operating an idiosyncratic database inside unity
that's improbable's strategy
you can get the source code to unity, and install mellanox adapters in your servers, and try to operate some kind of shared state view with a known latency
whatever is the HPC community's redis
Hey guys, I've heard that rigidbody manipulation is supposed to be done in FixedUpdate exclusively, but I've also heard that user input is supposed to be done in Update() exclusively. So where would the code saying something like "If I press D, rigidbody add force to x direction" go?
you can still query your inputs in update, set a flag and check it in fixed update. input system supports fixed update polling and may be the best option
clear the flag when it's been applied in fixed update
but input system does this for you already
so you're saying that input in Update() already does this?
no
you're right ytou gotta worry about this
Input System, a unity package
has some features for it
the reason this exists is because
if you had an action that was like, press a button
button down B
updates UUUUUUUU
fixed up. F F
observe that's possible that a fixed update by itself, in a naive case, will not "hear" the button being pressed
input system deals with this
it will correctly propagate the fact that you pressed a button forward in time
this requires knowing the difference between a button press (which should propagate forward) versus a mouse position (which should be whatever is the latest value)
or pressing a button twice should have 2x the effect of pressing it once... depending on how you define this to Input System
welp that's a lot more complicated than I thought it would be but I guess it is what it is
so by a flag do you mean like a boolean? Like for example, in Update I'd say "when I press w, set pressingForward to true" and then in FixedUpdate I'd say "when pressingForward is true, add force to the rigidbody"?
nvm disregard I'm just gonna learn the new Input system lol
Thank you that makes a lot of sense. However Im using the new input system now and though it’s disappointingly complicated for something so basic as input, I gotta learn it because I’ve heard this is where Unity’s going so it is what it is
tbf input is anything but basic
Hey if I have a XMLNode, how do I get its children as XMLNodes?
it's not that bad 🙂
ChildNodes?
Doesn’t that return xmlelement?
Isnt Element a node either?
Don’t think so
So whast the difference
https://docs.microsoft.com/en-us/dotnet/api/system.xml.xmlnode.childnodes?view=net-6.0#system-xml-xmlnode-childnodes
Seems to return an XmlNodeList which yields XmlNodes as far as I can tell? Why do you think it returns elements?
Elements is just a serialization of your nodes to get serialize into your target class. In xml code wise, its still a node within the structure
(Also, an XmlElement is also an XmlNode)
Just to be clear here: https://docs.microsoft.com/en-us/dotnet/api/system.xml.xmlelement?view=net-6.0 @honest hull
Oh ffs thx
Time to redo about 400 lines of code lol
I thought xmlelement had different functions and was a different thing than xmlnode
I have some custom packages. Core, Utility and some modules
Core package depends on Utility package and module packages depend on Core package.
How can I figure it out and resolve the dependencies?
A project can use some modules, for example Module1 and Module2.
I would like to add/remove these modules in a project dynamically according to requirement
Core => Utility
Module 1 => Core
Module 2 => Core
...
Does anyone use https://github.com/rlabrecque/Steamworks.NET for Steam Achievements? I'm using the latest release 20.1.0 via Package Manager.
I have a problem with CallResult<UserStatsReceived_t> never being received / my OnReceiveUserStats handler method never getting called, even though the request seems to go through - later calls to SetAchievement and other APIs that REQUIRE RequestCurrentStats being successfully completed seem to work at least partially (Achievement gets unlocked and toast pops when I close the game).
I store the CallResult in a class variable so it isn't disposed of by Garbace Collect and have confirmed SteamAPI.RunCallbacks() is called every frame.
// Steam API calls like SetAchievement or ClearAchievement won't work until
// RequestCurrentStats has been called and its result successfully received.
UserStatsReceivedCallResult = CallResult<UserStatsReceived_t>.Create(OnReceiveUserStats);
SteamUserStats.RequestCurrentStats();
Hey guys, Im trying to do an Automated System of Actions.
So my character/s do a set of actions (1-4) when their bar is full. I have a problem where, if they do an attack, and the enemy dies between actions, they still "Attack" the dead person. So trying to figure out how to change targets/stop all remaining actions on their turn.
file is a flowchart, and the SS is the actual Scripting
hello
do anyone knows how to get the exact rotation value in the inspector
i want TransformUtils.GetInspectorRotation but works on build
Keep track of the angles in your script
And don't cross post #854851968446365696
like what
give me an examples
im afraid that my question is gonna be buried so i changed channel
float x;
x += rotationchangethisframe;
welp there goes mine
oh nevermind i just found a solution
How do I figure out if my application is quitting in the OnDestroy() method? Can I do something smarter than this:
bool quitting;
void OnApplicationQuit() {
quitting = true;
}
void OnDestroy() {
if (quitting) {
//application is quitting; don't spawn more stuff
} else {
//application is running, proceed normally
}
}
What are you doing in OnDestroy()?
sending some signals
to other components
which should only be executed if your application is still running
yeah i think what you're doing is the only possibility
oh well :/
partial classes across 2 assemblies, any solutions?
what for?
trying to extend partial classes from a framework in my own assembly.
not so easy. you could use a asmref to link your scripts, but then they will be put into the extended assemmbly, not your own
you're talking along the lines of a sharedproject as an integration between mine and their assembly?
If there's any solution, it would have nothing to do with partial, because it doesn't work across assemblies.
apparently there are a couple of ways to run it but not simple (without needing to manually build a sharedproject every time you make a change)
https://stackoverflow.com/a/48277694
https://stackoverflow.com/a/61910792
I have a class library with all my database logic. My DAL/BLL.
I have a few web projects which will use the same database and classes, so I thought it was a good idea to abstract the data layer...
Do you control both assemblies?
Is there a recommended type of async class for doing level generation? Specifically with 2D tilemaps - I've heard you can run into issues with standard .NET threads making calls to unity functions, and IEnumerables slow down the logic dramatically
why async? are you after threading or ?
Yeah
Logic is too slow to do on the main thread as it freezes unity, ideally we will do it in the background whilst the player is doing something else (or at least display a loading bar)
before you go into using standard threading, try solving the task with Job system
oh so you are after async
Yeah
afaik you can split the jobs into chunks and run them asynchronously
looking at the docs now, seems you can schedule one and just not call job.Complete() so it won't wait for it to be done
there are several methods for async, c# async - allocates tasks, UniTask - non alloc if not threaded, More Effective Coroutines - coroutines but fast and non alloc
can you link?
to what?
i dont see any async specific api apart from scheduling and handles, is this what you mean? that they are running on a separate thread?
// Create a native array of a single float to store the result. This example waits for the job to complete for illustration purposes
NativeArray<float> result = new NativeArray<float>(1, Allocator.TempJob);
// Set up the job data
MyJob jobData = new MyJob();
jobData.a = 10;
jobData.b = 10;
jobData.result = result;
// Schedule the job
JobHandle handle = jobData.Schedule();
// Wait for the job to complete
handle.Complete();
// All copies of the NativeArray point to the same memory, you can access the result in "your" copy of the NativeArray
float aPlusB = result[0];
// Free the memory allocated by the result array
result.Dispose();```
If I never call handle.Complete(); then the job should just continue on it's own in parallel to the main thread right?
"Note: Jobs do not start executing when you schedule them"
So if you have to make the main thread wait by calling complete() what is the point of it being it's own thread?
that you can multithread your code
Surely if the other threads have to wait for one to complete you may as well just do it on the main thread though right?
its an api for doing effective and safe multithreading
Feel like I must be missing something here
no, you can chain together jobs
you establish a job execution hierarchy, dependencies etc, then run it all
you split the ms you spend in one frame over several frames reducing the frametime
Does the frame not hang on the Complete call?
does the frame itself not hang until it draws on screen?
Right
The whole point is I'm looking for a way to have frames keep rendering while this goes in the background
I think I'm missing something here
you have some workload that you can do over several frames
How does it get spread over several frames?
you can start the jobs each frame, allow to render, then start the jobs again
until your workload is complete
I thought that you have to call Complete() to get them to run, which halts until they're done
is that wrong?
you can also start them and just wait for them to complete while they run asychronously
aha! How?
yes, but you can setup it in such a way that you dont dump the whole workload into a single frame
Looks like Jobs won't work - they can't access reference types
jobs are designed for efficiency and safety
so you have to copy data, pass it to job in special containers
then copy it back to your ref types
I have access to both but their assembly may change rapidly
I'm not worried about thread safety much in this case... is there a more dangerous option?
it wont work in any case
Was hoping to avoid building my own structure and translating it
you would still have to create intermediate structures
do calculations raw then use the results on the main thread
I have a few, but most use things like unity's vectors etc
Gonna have to rebuild this logic from the ground up I guess
1-2 minutes on my PC
though our testers have had varying results, depends on hardware ofc
yeah thread awayyyy
assume potato, 2 mins is a lot, tho rimworld with mods manages to take half and hour to load on some machines
yeah for sure - hence trying to get it async
we need to optimise too but implementing that will be less painful once it doesn't freeze unity
if you just need async its completely different approach
you can use any method, it wont matter, like coroutines
you just need to intelligently split the load
i.e. approximate what maximum amount of ops you can do per frame on this users machine
you can do that iteratively, start with some approx max number, then reduce it until you have 16ms
I'm gonna have to refactor the whole thing anyways, may as well get it to just run on a true async thread with some custom data types
then use jobs
build some hashed tables to store the data etc which will speed up access
yeah
Thanks for the information
Hey, short question about LL/LR parsing,
does LL basically create the most upper node first, then the nested nodes, then their nested nodes etc,
and LR the most nested node first, then their upper node etc?
Or is that unrelated to LL/LR at all?
I've read quite a lot of posts, I've understood it as LL parsing the tree top->bottom and checking the tokens from left->right and LR parsing the tree bottom->top and checking tokens from right->left, depending on the current rules expectations,
but idk if that's quite right, I'd be happy if somebody could explain it to me in very short words
Anyone here familiar with using Animancer?
I have animation for a 2D blend tree such that I have 4 directions (no diagonals) but the diagonals work because they get blended from for example the right + forward animations.
The issue is that I have to use different left/right animations depending on whether I move forward or backward.
I am not sure how I can achieve this.
I've got an await using FileStream fs = new(...) that is properly waiting for the file to be found or created, but if there's an error (say, with permissions prevent file creation), it just keeps waiting forever. How can I set a timeout for this? After some number of seconds I want it to just throw an error and move on. Documentation online shows how to add a timeout for Tasks, but I don't know how to do it with this constructor
there should be a timeout parameter for anything that can work with a timeout
*overload
There's ways to set a Timeout on a FileStream, but I don't see a way to add one to the Constructor. I didn't even know it was possible to await a constructor
You don't await the constructor itself with await using, you implicitly await its DisposeAsync method that will be called when execution falls out of scope. So it would be perfectly valid to set a timeout inside the using block, as it will only await after the using block
I'm still not fully sure how to put in a timeout inside of the using block, I'm not sure how to get the Task object from that line to attach a timeout callback to
Or, wait, hang on, can I use FileStream's built-in timeout thing? Let me try
It could work, if it throws an exception when the timeout is reached it'll still exit the using block gracefully and dispose
Hm,
await using (FileStream fs = new(path, FileMode.Create))
{
fs.ReadTimeout = 5000;
fs.WriteTimeout = 5000;
//Do things
}
I put a breakpoint on the first line of this block, and one after this block, and neither is hit
what 4 directions would that be if you have to use separate ones for backwards?
does the path exist?
it is throwing an exception
No, that's one of the things I'm trying to test for
hmm
If the directory doesn't exist or there's permission issues, I want this to timeout so I can display an error
it is throwing an exception so neither breakpoint will be reached
i see
that's not what those timeouts mean
Yeah, that's what I was trying to ask about earlier, but this was the closest I could find
you can search async stat c#
on google
stat == checking if a file exists
might stop existing between when you check and when you use it
Is there a sort of catch-all error thing I can do for this? Try-catch doesn't seem to work. I can just display a generic "There was a problem" error message, but I want to try to catch all sorts of issues that could arise with it
don't overthink it. use File.Exists
or whatever it is in C#
you can run it in a thread and time it out. are you accessing external or network storage?
Network, yeah
It's actually being generated on a remote service. This is supposed to be creating a file I can then access on the network file system. I'm passing data and a filename to a web service that'll be generating something that can be used by an entirely different program on that machine
Checking if the directory exists is working, at least for the most common error case. I'm just gonna hope no one messes with permissions and then tries to run this again. If they never discover it can happen then it's not my problem
i see
look up the docs for OnApplicationQuit, it passes a variable. on windows, if the application is quit by pressing the X button, Alt-F4 or System.Environment.Exit(0), your OnDestroy is not guaranteed to be called
anyone familiar with photon?
what is the game?
The Parser is for something you could call a Modding Tool, not for a Game, it does have a Unity Context if you're in doubt with that 😀
If you were in doubt, dont worry, i think I know where I have to ask my questions, open for being teached upon that.
But the actual Context itself doesn't have anything to do with something that's probably a fundamental part of parsing 🤔
I'm by the way still looking for helpful Input, if anybody can try to explain LL vs LR in their own words or tell me if my understanding is correct
I'm not into networking, but I think I understand your question.
So, this is just my theoretical brainstorming:
Bodies may be linked to a AccessKey,
Players have AccessKeys,
Bodies are mutated only from the Server, changes through Local Players are made via sending the Input to Server and processing it there.
If a Player disconnects, his AccessKey gets stored somewhere, locally. The body will stay present for X time and any mutating by Server and other Players can still be done.
If the Player reconnects, it will, if any, pass the stored AccessKey, if the Body with this AccessKey is still present on the Server, it will reconnect.
I don't know if that would be a working concept, but sounds logically to me
Also, sorry, but #archived-networking
Thank you for the help, i didn't see the networking my bad. 😅 @remote pumice
it's hard to help you without an answer to the question
Hey sorry for the super late reply. I dont want them to share the same account. Lets say only for the ios . If i have in app purchases is it safe to just save the info locally? For example that the player purchased a skin. Isnt this hackable , letting the somebody change the binary files and enabling all skins? How do I make it retrieve info from The appstore that they actually purchased the skin or achieved the highscore etc
are you asking how do you implement IAP on iOS?
prime31's ios store asset lets you implement IAP on iOS
all the store assets support checking a signed receipt from the platform
you wouldn't implement this yourself
why would vulkan crash on linux with no screen, but directx & metal do not?
For optimization on the HoloLens 2, Microsoft suggests I use this.
However, based on the docs, I'm not quite sure where to change it.
You just write it in any class
Must it be attached to a gameobject?
I mean that depends how you do it, but yes if you use a MonoBehaviour class
What's the option?