#archived-code-advanced
1 messages ยท Page 163 of 1
for some reason I cant give it an actual color as a default
this is in rider even
Well no, you need to feed it the type to default
Color is a struct I imagine
You literally need to do default(Color)
Like this isn't a placeholder
You need to do exactly that
But it looks like Color is a class anyway?
The default for classes is null
For clarity I'd just use null then
Thanks a lot bro, that makes a lot of sense and it worked in monoDev
I give up, endless problems:
This is supported in C# 7.3+
s_instanceBehaviourManager doesn't even bring up a single Google result, but it's in the UnityPlayer's debug symbols
You can ask on the forums but you might not get a good answer
I figured it has something to do with instantiating MonoBehaviours, which would help me a lot with reading a game's memory (for speedrunning tools)
Hypothetically, shouldn't be I able to connect to another device on the same router if the port and ipv4 adress are correct?
It is perfectly fine when it is localhost
I'm trying with a Mac and Windows
In Windows I checked firewall settings everything is allowed
I just checked Mac and the firewall is off
Dunno whats the problem
I'm having a few errors here building my game... but these errors aren't making any sense, they're talking about a script I haven't edited since waaay before my last build and am really worried
you probably accidentally removed a semicolon
all of the 'public' errors are pointing to functions that kind of need to be as they get called a fair amount... and the missing '}' is the one at the end of the script that IS there
no actual script is giving me errors, I just get this when trying to build
mind to share the code?
not at all, but it's quite big? and it's talking about a lot of different things going on haha
so I wouldn't be too sure on WHAT to share
as VS doesn't say there's any problems
Well, I have no idea what to say then
Something I realized. Every algorithm could be O(1) if we could code in future sight into our programs. Most algorithms start out not knowing the answer, and have to spend compute energy to find it. Future sight allows us to know the answer before computation.
Most cheat by caching results but this still requires spending that compute energy once to get the performance gains.
thats the whole idea of stochastic approaches and ML (also stochastic), they try to invent an oracle
Did anyone here play with the experimental collision contacts modification api?
Wait, really? Have any suggested reading on this technique (will google right now as well). I was just making a joke that is kinda funny only if you know what I'm saying.
you could even say that all algorithm improvement stems from understanding the properties of a problem so well that you can make predictions what can and can't happen and develop a new algo around that
the O(1) compute but O(crazy) space is also tradeoff that we happily use in gamedev via baking and any kind of LUT/caching
not sure what to recommend here... its an opinion/perspective i formed after studying ML and advanced algos in Uni.
Lol @ O(crazy). I was studying more of the gameaipro book 1 book and they talk about strategies of reducing computational load of pathfinding. One strat is to bake in all possible routes an ai agent can take at compile time. Spend those CPU cycles up front so others don't have to at runtime
I appreciate that. I'm reading https://www.manning.com/books/advanced-algorithms-and-data-structures now. I hope they take about what you have studied before
As a software engineer, youโll encounter countless programming challenges that initially seem confusing, difficult, or even impossible. Donโt despair! Many of these โnewโ problems already have well-established solutions. Advanced Algorithms and Data Structures teaches you powerful approaches to a wide range of tricky coding challenges that you c...
maybe look at stochastic solutions to SAT type problems
looks like it
Well thanks for getting my joke @compact ingot . Going back to reading. My plan is to read a bit then work on my machine setup/productivity CLI then do some game programming. Cheers!
looking at the TOC of that book it seems that there is a lot in there about optimization approaches and why they work
later chapters seem to touch stochastics
Hi I have a question about code structure.
Mainly about where the "logic" code should go.
My set up relies on unity's mecanim animator state machine and the new input system.
The mecanim helps me to keep code out of my player class.
The new input system feeds input to my player class through the use of methods.
I'm trying to figure out the best way to use these two systems together instead of fighting each other like they are now.
The tutorials showed me that I should have add methods with the logic that I want to run whenever there is an input response event...
But I'm also using a state machine so I don't know how to make these two work together.
Right now whenever there's an analog or directional key input the playerclass feeds that direction into a vector var
The animator walking state(the default state) is reading the vector var in order to change sprites, it's also checking other keys and performing checks to see the player can transition to jump, atk etc.
My question, is what kind of code should I put in each system?
Here's some code snippets of what I tried to do:
https://www.toptal.com/developers/hastebin/veqiyasuqe.csharp
https://www.toptal.com/developers/hastebin/kubumibape.coffeescript
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
the problem I have mostly is with button presses.
say for attacking, the input system provides a value, lets say for attack button it sets attack bool to true, then the state machine, reads it and has to set that value to false.
I need to do this set up with every new state i create
all the overhead it causes kills me lol
personally i would try to keep logic as far away from mecanim as possible and use it (mecanim) only as a way to read what the result of my logic is and how to animate it
I am attempting to make a dictionary of methods that can take variable unknown parameters. the goal here is to tie a enum to a function that does whatever I need and takes whatever parameters it needs to do it. This is what I made so far using generics but it feels really hacky. Any ideas how to execute this correctly?```
public class DB_DialogEffects<T>
{
public delegate void Method(List<T> args);
public static Dictionary<DialogEffectType, Method> methods = new Dictionary<DialogEffectType, Method>()
{
{ DialogEffectType.none, None },
{ DialogEffectType.setFlag, SetFlag },
};
private static void None(List<T> args)
{
return;
}
private static void SetFlag(List<T> args)
{
Data.flags[(Flag)(object)args[0]] = (int)(object)args[1];
}
}```
so I should just make my own state machine?
probably, its what i would do. but that doesn't mean its right for you... building your entire project on top of mecanim (which is made for animation, not for logic) if it isn't a pure animation player, seems wrong.
well it's supposed to function as a state machine
you can add behaviors to each animation state and each animation has it's own update
probably best that you try to do it and see if it works out. its probably not what most people would do however.
well it does work, I was just wondering if I could make it work better
๐
which also means, you have to rebuild stuff in a better way
figured as much, that was also what I was asking originaly
๐
i like this as a general purpose statemachine https://github.com/dotnet-state-machine/stateless
if you need a visual tool, i'd go with (reason being primarily its neat UI and the features to make it designer-friendly) https://assetstore.unity.com/packages/tools/visual-scripting/nodecanvas-14914
seems like it wouldn't help much
the unity state machine works
I'm just wondering where the main driving logic should go
i think i don't understand the question
I'm wondering how I can make the input system work better with my current state machine
hey! Sorry if I misunderstood, but are you asking where to put the logic that will set the parameters of your state machine for transitions?
like having your inputs set parameters on the Unity State machine?
yeah
what should the state machine do and what should the inputs do
right now I have it so inputs feed into variables and the states read and do stuff with those variables
Oh well that would be the correct way I think!
Like having a script that listens for your inputs, and send parameters accordingly
So you'd have a PlayerInput component if you're using that, your InputToParameter scripts containing the logic to take an input and send a value to the animator, and the actual animator doing its thing?
yeah, but there's also physics to take into account, which muddies things up too
since the states don't update in fixed update I'm doing a lot of messy work arounds
so I have a fixed update in player that reads other variables that the state changes
I'm wondering if that's ok too
I'd show my player class but it's already at 1,300 lines long lol
yes sometimes, with private values in the player class I made methods in the player class that the state runs and sets those values
ok so your player is modified by the state machine, but the player also sets the state machine parameters right?
ok I see! I don't think there's anything very wrong with that (I haven't seen your project so I can't say how I would handle it) but if it's getting in your way, what you can start doing is decoupling the values that the state machine sets and the player class. So you have one thing that drives the state machine, and one thing that receives parameters from the state machine. But in the end the player will have to read this parameter receiving thing, so it's going to work the same way, just in different scripts
ah, maybe I should use generic types, is that what you mean?
Basically if your goal is to reduce the size your player class, you can start splitting it into multiple components so that not everything has to talk to your state machine
yeah like I have a state where the player is invincible after taking damage, right.
so I need to make a method in the player class so I can change my private hit box
if I'd make an all usecase method would I use a method that takes in a delegate?
For these kinds of behaviours, I'd avoid doing very generic stuff because you seem to have a bunch of different things that need to happen depending on the value
Using one method you'll end up with a huge amount of code
So here's what I would do for the damage thing:
I'd have a health component, which would take care of the player's health and taking damage. So this component would listen to the state machine, and do whatever is needed explicitely. So you can have a method in it that says MakePlayerInvincible() or whatever you want
That way you can start taking that out of your player class
Which is gonna make your code more modular and easier to read
ah good call
Basically I'd encourage you to find what the player class should be taking care of. Should be 1 or 2 things at most. So for example it could simply be the movement.Then if you have an inventory, add a inventory component, and so on
I think it's better to have a lot of components rather than a lot of code in a single component
And this will help you I think because that way not everything has to talk to the state machine all the time
when you said I'd have a health component, which would take care of the player's health and taking damage. So this component would listen to the state machine
I'm not sure how to make a seperate component interact with unity's state mahchine actually
right now it's heavily tied to the player
It's been a while since I've done state machines using the animator, but isn't it simply getting the animator reference and setting a parameter?
Say you have a gameobject with your state machine on it, with the player and health class
both player and health can have a ref to the animator running the state machine
(I think, again it's been a while haha)
yeah in the awake method you can do GetComponent<Animator>() and then SetBool/SetString etc... on it?
ok, so the animator moves to the damaged state, and the behavior would have a reference to the health component right?
or maybe the player class can fill that dependency on awake
I have a lot of refactoring to do lol
haha yeah I spend a lot of time refactoring
it's good practice
and your Health component could get that reference itselft
so is the health component checking if the animator moves to the damaged state?
I was thinking that the state machine would have a reference to the health component
{
public float Health { get; private set; }
private Animator _stateMachine;
private void Awake()
{
// Get ref to the state machine
_stateMachine = GetComponent<Animator>();
// Set default health
Health = 100;
}
private void TakeDamage(float damage)
{
Health -= damage;
// Here you can call your state machine and tell it you took damage, triggering the transition to the invicible state
_stateMachine.SetTrigger("Player Took Damage");
}
// And this could be called by your state machine directly when the invincible state needs to be triggered
public void MakePlayerInvincible()
{
// Do stuff to make the player invincible
}
}```
here is what I was thinking
oh I see, I was thinking backwards lol
The state machine needs a reference yeah to the Health class
unless you're using a messaging system
(which I'd recommend btw, scriptable objects are amazing)
(omg I love the idea of using the animator state machine as a state machine for scripting logic.)
๐ฎ
It has it's drawbacks but it works well enough
On first blush, it seems like a good way of dropping the number of collaborating systems by one. I usually code up a new FSM for every project I create that needs it, and it usually interacts with the animator component. But managing those interactions between scripting FSM and animator FSM is sort of a (small) hassle.
The idea of putting the animator FSM over scripting logic is an idea I haven't ever really thought to explore.
there's a lot of stuff the animator does, it's pretty crazy
Again on first blush, I could see animation clips reaching out to functions that ultimately fire off events as a way of allowing animator's FSM to reach out to more complex code.
That way in automated tests I could create an event that fires ultimately from the animator's FSM to test whatever the attached logic is.
I'm a little self conscious that last message might be too terse. I think linking this would help some understand what I'm saying a bit more: https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html
That describes how animation clips can call logic contained in a C# script. I am describing having animation clips call a C# function that ultimately fires off an event (or a delegate) that event consumers can listen for. The animator FSM would then be composed of the animation clips and then one can think of the observable side effects of the FSM as what events get triggered.
that would help keep things tidy
not sure how to make other classes listen to it tho
Animator needs to be saved locally.
Two techniques: either the event listeners are on the same game object, and the event listener scripts subscribe using GetComponent ... or you design the events to spell out what game object they're attached to, and all event listeners would see if they are the game object the event is for and if so, run the logic
why on earth would you want to use the terrible mecanim state machine and animation events for this kind of stuff? what benefit does it provide?
So I can know what each state does and I can edit them easily
seems to me this immediately makes it extremely annoying to debug logic flow and make changes to the logic down the line
the alternative is having a player class full of methods
I'm trying to move things out of my player class
then do that, but the mecanim fsm is not required for that at all
why
you can just make a new class or component reference that from your player-class and put logic (i.e. methods, event and whatnot) in there
the calling of those external components can be driven by an fsm, but i would not ever use the animator fsm for that
it works pretty well though
its just too cumbersome to debug and read what it does
Different things should be split across different classes.
If you try to cram everything into one class you are sure to have issues.
It's always been a standard practice to split logic and draws or animations into different classes.
Something that is used in multiple classes needs to be it's own class.
Like an inventory. Clearly a player has an inventory. So does a storage node. So does an NPC
I don't see the anim state machine as just animation, it's splitting actions into their own behaviors, it prevents me from dodging while I'm attacking
Thats pretty much what I hate about new world so you go for it.
every state is it's own logic
I can have dodging while attacking if I wanted to, there's nothing preventing me from doing that
it just helps me keep actions in their own separate behaviors
The point is if you want a local variable you need to do something like anim.getFloat("SomeName"); if I recall
Someone mentioned this in one of the other channels recently and it was stated that it will slow the game logic down
thankfully my game isn't demanding
It's possible I guess by all means give it a try no reason to discuss it any further either you will or you won't.
pretty much
Hello. I am very curious about making Circles with LineRenderer.
A first-thought approach, will leave a cut or missing segment between the Start and End positions.
This can be fixed, crudely, by enabling Loop.
I have made an optional workaround, which only works for circle shapes.
(by giving the last position the same X and inverse Y position as the previous.)
I would like to perfect the approach, so I can make perfectly formed shapes - Triangle, Square, Pentagon, Hexagon +++
And I wonder if someone here can point me in the right direction.
Right now I'm contemplating whether or not the issue lies with the lacking precision of floating point numbers while making calculations with PI.
Throughout the day I've been thinking maybe I need to add a float TAU and subtract the length as the line positions are created, and lastly adding or distributing and restructuring the points based on the remainder in float TAU.
Perhaps simply the difference between Mathf.PI and Math.PI ๐ค (which seems impossible)
I want to share again that I support this attempt to use the animator FSM as the driving FSM. Animation clips are relatively easy to reason about for designers and developers. Thinking about the states of a game character from the perspective of the animator's FSM buys you a free UI representation of your FSM.
My only concern are the animator transitions. If one cannot define customized animator transitions then I see that as a downside of this technique. Fortunately, it looks like one might be able to define custom using this urls [0] [1]. Maybe all one needs to do to define a custom animator state transition is to define an editor script in a project's editor directory? Hmm ๐ค
[0] https://docs.unity3d.com/Manual/StateMachineTransitions.html
[1] https://docs.unity3d.com/ScriptReference/Animations.AnimatorStateTransition.html
I'm gonna go insane lol someone help me
Debug.Log(LocalPlayerPrefab) works just fine
that Instantiate line literally does nothing
No errors
Nothing
I put that line in another method, works just fine
I'm changing scenes, and this method is on a Don't Destroy On Load object
Literally why is this?
https://github.com/search?l=C%23&q=AnimatorTransitionBase&type=Code Maybe there is something within this ~200 results that show how to do what I described in my prev message
Are you sure it isn't getting instantiated? Based on what code you shared, it should be at -25,5,25 in your game world. Double check if the inspector shows a new game object in your scene when that code runs.
edit
DDOL stops the gameobject and its children from being destroyed on a scene change. Are you instanting this in a new scene, or during the frame you try a scene load?
Also it should be at -25, 5, 25
I instantiate these objects with a script on a new scene
And this script is on an ddol object
That is from the previous scene
the DDOL is irrelevant, since the thing you instantiated isn't a child of it
objects get instantiated in the "active" scene
Yea I know I added that in case there is a known thing about that
player = new GameObject();
This does nothing at all
also
the scene you're creating them in is probably destroyed a frame later. What does the callstack for SpawnPlayer look like?
How is it called?
Because you probably are doing LoadScene somewhere, which has a one-frame delay
there you go
- You tell unity to load a new scene. It will delay until frame is over
- You spawn your player in the active scene
- after frame is over, Unity loads the new scene, destroying everything in the old active scene including the objects you just created
ah
add a delegate to SceneManager.sceneLoaded, and put your other logic there
or run it in a coroutine that delays one frame (on your DDOL object), that'll work too
yield WaitForEndOfTHeFrame
no, that might be too early still
huh
yield return null
I solved it ty man
Hello! I'm trying to make a cross-platform game that is fully moddable (I realize this is a vast undertaking, so for now I'll settle for something like a barely functional prototype where you can instantiate objects and move them around, and that's basically it; this prototype should be easily doable).
From what I can gather, with Unity this is exceptionally difficult. First, loading runtime assemblies isn't even supported in iOS. Second, there are some limitations on this workflow.
Am I basically stuck rolling a full blown game engine inside unity and gluing stuff together with lua scripts? Basically the entirety of the game's logic would be lua scripts calling compiled Unity stuff
"Rolling a full blown game engine inside Unity" would be against the Unity TOS
You can make a game, with a scripting runtime (such as LUA), with bindings into your game systems
@sly grove
I didn't realize that one. Yeah I imagine I can't allow users to do to much, there's probably some gradient where if I allow them to script an entire game that would violate TOS
And thanks, that's what I imagined. Damn there's no way you're going to get good performance with that
Is there a way to access the join as host/client/server functions in netcode from another script so I can just slap some buttons on my main menu or even better check if there's a host, if not join as host and if there is a host join as client?
I mean yeah, just make a public function that calls those things
The problem is these things are in a script and i'm not smart enough to understand the networking code
so i was wondering if netcode comes with a special function to start as host/server/client
@sly grove sorry to bother you, but would you recommend moonsharp as a unity embedded lua interpreter? It seems nightmarish to roll my own or try to do this via a separate process
you can also just let your users decompile your code, add the modded behaviour and let them recompile
@drifting galleon I actually won't mind if they do that. Afaik thats how early Minecraft was modded right? If they want to do that they'd be free to.
@sly grove thanks!
i am also very interested about how to create a full native modding api, unfortuantely i haven't got any real info about the workflow though
Designing the base game as a mod should be the default flow there imo; everything logic should be moddable from the very first thing you implement
This isn't technically necessary but it makes it easier
Okay I really need to figure this out
Idk where to even start to fix this
Whenever I click AttachToUnity it gives me a crap ton of errors and doesn't work
Actually it seems like LeanUI is the problem
Idk how to fix it though
They all seem to be related to missing namespaces
I doubt LeanGUI messed up this bad though
Good old delete and redownload of LeanGUI fixed it, Im good
how do I make a skinned mesh renderer switch shadows to cast only and not actually show the model through code?
public SkinnedMeshRenderer playerRender;
void Start()
{
playerRender.shadowCastingMode(ShadowsOnly);
}
this isnt how you do it but this is the idea im trying to go
the unity scripting documentation only shows the names so I know its shadows only they just dont give an example
shadowCastingMode is a property. Did you try playerRender.shadowCastingMode = Rendering.ShadowCastingMode.ShadowsOnly;?
oh is that how youd o it
rendering isnt a thing that I can use
is there a different syntax for that
What would be a better way of coding rather than using loads of if statements? Which could end up with code being a jumbled mess, like the example belowif (isGrounded== true) { if (isSprinting== false) { if (weaponInHand == null) { Jump(); } } }
enums, or state machines, or hierarchical state machines
in this order
@olive star ```cs
if (isGrounded && !isSprinting && weaponInHand == null)
Jump();
beyond removing those nested conditionals that you don't need, an FSM would be the next step to clean stuff way up... a nice one can be extremely neat, but it can't handle complex, overlapping states, for that you need if-statements again, or a different 'machine' model that makes overlapping states clean
Ok, I'll have a look into state machines. Thanks for the help to the both of you!
I'm curious, how would you handle these combinations of states in a state machine? I'm not seeing how you could even do that. I know that in a HFSM model his code would have the [weapon in hand] nested inside [is sprinting] nested inside [is grounded]
But how would you approach the problem using your idea?
like you say, either nested or discrete states for each
@dapper girder the other approach is too complicated to explain here in detail, but the api could look like this (this is for a RTS style camera controller):
and in the background this would use set operations to construct the boolean expressions based on that config (in the screenshot) and evaluate which "aspect" can be active in any given frame
this looks really nice actually, I've wondered how to do this before but seeing this shed some lights
I am trying to understand whether a particular differnece exists between unityevents and c# events,
So, is this correct: UnityEvents do not require references to be coded into either the sender or reciever, but c# events require the reference of the sender to be present in the code in order to subscribe to it
I am trying to remove references from each script, but i have seen in several tutorial videos that you need to reference the sender to be able to subscribe to the event, but if you are using unityevents, you do not need any references in the sender or reciever script,
is this true/
?
How do I attach particle effects to tiles in unity? And is there a way to code such that I go near certain tiles and they disappear?
I probably can't answer at a super deep level, but what I can tell you is my perspective. So when I have to decide if I want to use unity events or c# events, I usually ask myself: is this something I want designers (aka me) to easily be able to attach listener functions through the editor inspector?
Depending on that answer will decide if I use them. That's because I see unity events as something I get free editor UI. Otherwise, I see them as functionally equivalent. Yes I know that unity events are less performant than regular ones. I also think it is a worthy trade to sacrifice some performance to buy certain affordances.
It depends on what gameplay user story you are solving for. There are plenty of ways of "attach(ing) particle effects to tiles in unity" so you may have to be more specific.
And is there a way to code such that I go near certain tiles and they disappear
Assuming the "I" in this is actually a player, the answer is yes. Even if it literally means just you (aka your player avatar that you use to inhabit a game world), the answer is yes as well. You can do anything you can imagine, within reason!
Is this a custom library or is this default code? Looks very interesting for a camera behaviour, can you explain me how this is created? ๐
this a custom data structure; implementation: https://gist.github.com/gerolds/b2a63ece0d2a088bf5564c7a5af092b8
Thanks, i will have a look
@regal olive I see. I haven't yet used both of them, but i would like to ask something regarding the normal kind of event. When using unity events so far as ive seen, we do not require either the sender or reciever to have references to each other, however, since you seem to have experience using the c# events, do you usually have references to the sender in the reciever script in order to subscribe to the event? because my objective is to remove hard coded refernces as much as possible, so i would like to know if references cannot be avoided when using c# events
Okay between this and the screenshot I have to ask... what is this? Or maybe, what are some good terms to type into a search engine to learn more?
Aspects? LINQ like API. Lol wot
No! Not at all. The sender should not know about the receiver.
The receiver can know about the sender to subscribe to the event(s). Another approach is to use an event broker so the receiver doesn't have to even know about the sender.
aah i see, so there is an option to avoid the refernces. Thank you
this is a model i invented so you probably wont find much by googling. the principle is inspired by declaration of facts and derivation of truth states from those facts (similar to programming in Prolog), all this is driven by the equivalence of boolean logic with set operations and the construction of horn clauses from those sets. The API is designed so you can arbitrarily add rules that must be satisfied for an (re)action to occur without having to think hard about what a valid set of boolean expressions for all those overlapping rules would have to look like. So imagine your designer wants a new rule, you can just add that rule by spelling it out and the system will activate it whenever that rule is valid and not contradicting other rules. An extension of this model could be based on modal logic (e.g. utility functions or temporal operators). you could also think of it as an inverted state machine.
// public class bulletSettings : MonoBehaviour
{
public float speedX;
Transform trans;
CharacterMovement character;
void Start()
{
trans = GetComponent<Transform>();
}
void FixedUpdate()
{
if (character.right)
{
trans.Translate(new Vector2(speedX * Time.deltaTime, 0));
}
if (!character.right)
{
trans.Translate(new Vector2(-speedX * Time.deltaTime, 0));
}
}
}
when my character looks right it shoots left
this is 2d
Did anyone encounter following error before? "Cancelling DisplayDialog because it was run from a thread that is not the main thread" It trashes my entire engine...
I have insanely long build times since the error occurred and unity wont properly close after closing the unity window. It says cleaning up engine and does pretty much nothin.
Also the error always comes up after building the game. (I can consistently reproduce the error)
It needs a vector3. try doing it like this :
if (character.right)
{
trans.Translate(Vector3.Right*speedX*Time.deltaTime);
}
if (!character.right)
{
trans.Translate(-Vector3.Right*speedX*Time.deltaTime);
}
``` sorry about the identitation
where should i put this script
replace it in your own code
add it?
{
public float speedX;
Transform trans;
CharacterMovement character;
void Start()
{
trans = GetComponent<Transform>();
}
void FixedUpdate()
{
if (character.right)
{
trans.Translate(Vector3.Right * speedX * Time.deltaTime);
}
if (!character.right)
{
trans.Translate(-Vector3.Right * speedX * Time.deltaTime);
}
}
}
it should look like this
thanks man ๐
no worries, tell me if it works, haven't touched 2d movement in quite some time
okay will do
Hi, I'm making a bird simulator in VR. Currently im applying rigidbody force to the forward. When I then want to rotate with my wings, the force applied to the forward is still going in the previous direction, which makes me go in the wrong direction. How can I turn with a forward rigidbody force? I've tried to apply force from my left and right, but that doesn't turn me, that just moves me left to right.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MelonLoader;
using UnityEngine;
namespace MyMod
{
public class Makethemod : MelonMod
{
// Duplicates fixeddeltatime and makes paused variable
public float fixedDeltaTime;
public bool Paused = false;
public override void OnApplicationLateStart()
{
// Makes this.fixeddeltatime and time.fixeddeltatime the same
this.fixedDeltaTime = Time.fixedDeltaTime;
}
public override void OnUpdate()
{
// The actual input
if (Input.GetKeyDown(KeyCode.Space))
{
if(Paused != true)
{
// Pause the game
Time.timeScale = 0f;
Paused = true;
LoggerInstance.Msg("time SHOULD slow");
}
else
{
// Unpause the game
Paused = false;
Time.timeScale = 1.0f;
LoggerInstance.Msg("time SHOULDNT slow");
}
// Apply previous change
Time.fixedDeltaTime = this.fixedDeltaTime * Time.timeScale;
}
}
}
}
anyone able to tell me whats wrong with the time stuff in this? i know the input isnt wrong as i get a console thing whenever it is pressed, so it must be the time
hello, I'm looking into making a final fantasy tactics-like in 3d but with 2d looks/sprites, is there any tutorial that I could follow?
- #854851968446365696, "Search the internet for posts with the same question".
- This is #archived-code-advanced, where loads of explanations and debugging is expected. If your question is not about specific code (too general), ask in #๐ปโunity-talk instead.
thank you
Just so I understand, what is the expected/intended behavior?
pause the game
when spacebar is clicked
Seems like that would do the trick. Can you Debug.Log(Time.fixedDeltaTime) at the end to ensure it is set correctly when the time scale is 0?
is there another part of the game which perhaps immediately changes it back?
I'm trying to load images from resources and put them on buttons, but the image is coming out empty. Any ideas why? https://pastebin.com/t5YXqSHz
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.
The name debugs correctly.
time.fixeddeltatime is 0.0001
It seems like you're successfully stopping the game time. Is there specific behavior that indicates otherwise during gameplay?
not sure, its a mod so ill need to look through
That's awesome. I love thinking up appropriate (mental) models for my code. I try to think of affordances and signifiers. That said, I don't often see people applying epistemology and other philosophical principles to arrive at useful code. Really cool, no lie.
Just reread this question, yes. The cars, enemies, actions, everything keeps moving
I assumed enemy movement was based off time.deltatime, because usually you would times a transform by time.deltatime, but i may be wrong
#๐โfind-a-channel, your question has no relevance to code, never mind advanced code
Good call, I'll take it to unity-talk
happy you like it. Not sure if was inspired by philosophical principles, but it seems to me those overlap quite a lot with the stuff you do in symbolic AI. And in phil., from what I understand, reasoning works essentially the same way as mathematical proofs do.
Anyone know why System.Net.WebClient()'s "DownloadString()" would succeed in the Editor but fail in a standalone build?
maybe a few more details on how it failed? Error, timeout, ...?
No errors, no timeouts
did you await the result?
Its super weird, I'm trying to debug it atm, putting debug.logs in my try and catch block, trying to output the webexception.status as well
did you check for errors in the thread?
yeah, none
Right now I'm not even seeing the standalone player going into the try block
are you actually calling the method?
if that code runs in a thread, i might hide an exception
Its being called yes, if I run it in the editor it populates my text field, when I run it in standalone it doesn't.
maybe step through it with a debugger?
I haven't messed with standalone build debugging, might be time to figure out how to do that.
works almost the same as editor attached debugging
I'm trying to create a 2d lighting system like among us, where certain things are hidden in shadows. I followed a guide for a custom shader on Stack Overflow (https://stackoverflow.com/questions/65696260/is-there-a-way-to-hide-a-player-who-is-in-the-shadow-in-unity-2d-light-system/67780057#67780057), and I got it working. However, even in shadows, my character that has the shader applied is still slightly visible in shadows, even though in the stack overflow example, he is completely invisible. How do I fix this?
Curious if anyone knows the technical reason that there is a HUGE performance cost when you reference an object that's set to null?
Obviously its a glitch that you need to fix anyways but it keeps surprising me it can lower fps by like 30-100 depending on how many instances you have of it on tick.
if you get a null ref, it has to propagate up the callstack, where it will be caught in try catch, if not by you then by unity, which will then dump it in the logger, which the console will display as a message, and console spewing out lots of messages is bad, shouldnt be the reason for low performance in build by itself, if you observe that then the problem is your code that relies on the value to not be null
there isn't
you can't use WebClient in unity, use UnityWebRequest
this isn't the right approach to retrieve an external IP
it won't work
you just shouldn't do it
apply angularVelocity
i.e. an angular force, i.e. a Torque
Yes there is - it's when you get a console error. I had a 100fps drop when I put 100 of my character prefabs in the game to test performance but then I realized that 90% of the performance decrease was from an error I had unresolved on tick for every character and the profiler was showing that the callstack printing string was responsible.
The performance drop was also not visible in the build.
@plucky laurel had the correct answer. Thanks!
hi! may i ask if it's better to create a pool manager for each type of object or just have one? im going to be using one for creating projectiles, one for managing item loot drops, one for enemy spawning, one for some vfx of the player skills (like a dash with after image effect)
Ohhh so I should create one for each type of object and have a manager be the one to access those pools and whatnot? Alright. Thanks!!
Actually it does work, and Unity supports all sorts of System.Net functions along with other .NET functions, so saying that you can't use WebClient is just wrong. I found the fix, Unity was set to "Low" for Managed Striping Level, disabled it and everything works again. Looks to be a bug in 2021 striping out Managed .NET code that it shouldn't be. Opened my old project on 2019 and it worked with Low striping. Already emailed UnityTech a few times back and forth, hopefully get things fixed in a future 2021 patch.
Also interested in seeing your "correct" approach to getting an external IP. Assuming it'll be a Coroutine with UnityWebRquest, which also works, but not looking for a Coroutine for this application.
Hi, I'm facing a bit of a problem. My character jumping is like mario jumping. The longer you hold the jump, the higher you jump. But I want to add a bounce stuff in my game. that launches you up when you jump on it. Problem is, if you hold the jump again after you just bounced of that thing. it just launches you into ridiculous height. I noticed this line of script is causing it. But removing it also removes the fall speed and multiplier of the fall speed. So, how do I disable the option to hold the jump after player just jumped on the bouncy stuff?
{
rb.velocity += Vector2.up * Physics2D.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
}
else if (rb.velocity.y > 0 && !Input.GetButton("Jump"))
{
rb.velocity += Vector2.up * Physics2D.gravity.y * (lowJumpMultiplier - 1) * Time.deltaTime;
}```
When I used torque it didn't change the direction for my velocity, thus still going into the wrong direction
Have you tried rb.AddForce?
Just got it working. But thanks.
Anybody have a good set of references to start learning how to write shaders in Unity? Thereโs a lot of info out there but I canโt find a single source that sort of lays it all out.
also shaders aren't overly unity-specific you could also look at generic shader resources
Thanks guys
funny, this thing goes from the basics of unity to compute shaders within the first 5 lessons.
Are you working on a game?
freya holmรฉr is great for getting going with shaders specifically in unity https://www.youtube.com/watch?v=kfM-yu0iQBk
Try setting the angular velocity
just rotating the transform works
Whatโs your objective? Whatever you can solve with shader or VFX graph is best
Is it important that your rigid body behave physically?
i want to use a compute shader to generate and evolve a giant 2D terrain/game map and then use a pixel shader to render it, including programmatic LOD
only problem i have is when I want to slow down the rigidbody when falling by adding force up, it will eventually fly up
doing it first in the browser as a shadertoy will be easier and faster
Then once you have a result there much easier to port to Unity
@thick thorn also https://thebookofshaders.com/, https://www.ronja-tutorials.com/, https://learn.jettelly.com/unity-shader-bible/ are all solid resources (the last one is an e-book that costs a bit of money though. others are free.)
All the unity specific stuff sort of becomes useless if you are doing your own rendering
If I understand correctly
You want to produce your own rendered image directly
And not participate in the unity scene graph meaningfully
Anyway as a professional I am most interested in people who know shader graph or VFX graph
Instead of โshading languageโ
To make mastery of shaders valuable you have to be a really good programmer
Whereas itโs immediately obvious if you can make a good looking material or VFX effect
that's interesting. would you say it's helpful for people who use shader graph/VFX graph to have a core understanding of shading languages?
So if itโs for education purposes itโs best to visit computer shaders and such when you can program well enough to use them
Not really because they should be mastering using their eyeballs
What I mean is that I donโt think the idiosyncrasies of shading language help you make stuff that looks better
Those are great resources though
That you linked
oh cool. yeah that makes sense
And even compute buffers are sort of useless because of limitations of Metal on iOS - Unity Jobs has a better hope there
Not totally useless butโฆ on PC you can do anything, and on the performance constrained device they donโt work
I want when the frisbee collide with the collider it should flip back and move back in a curve like a natural frisbee. I have made a strategy to take the animation curve in the inspector. And give it a parabolic shape. When the frisbee collides with the collider then the coroutine starts which implements the curve logic. But there is an initial DoTween movement in the game which is moving the frisbee on right. The curve logic has not canceled that movement suddenly. The curve logic is only starting once the frisbee finishes its DoTween Movement and curve logic is also applied in a very weird way.
Here is the code.
https://pastebin.com/8b7xbuZr
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.
Ive been learning HLSL the past few months and thinking of jumping over to the graphs later. But the reason i wanted to do it in scripting first was to understand the shader structure and how it actually works. Do you think i should jump over whenever i feel confident enough to read and understand it or should i start using the graphs right away?
So i have to dinamically load around 4 scroll rects that contain 100+ sprites with buttons assigned to them. I have a few questions - is that alright to do, or should i find a better way to check each sprite for clicks? Also when i start the game in unity, sometimes it runs smoothly, sometimes the perfomance is very bad. Any suggestions?
i can program pretty well and i also have intimate knowledge of gpu architecture from my job
i was going to use unity specific stuff for input, UI, etc, and other parts of the engine. the original plan was just to render to texture and have a single image displayed on the screen with the rendered texture. but if there's a better way, let me know
i'll take a look at shader toy though
you should start with graphs right away
that's a good idea
if you're going to innovate in this way of rendering something maybe focus on that
and if it looks good, if it can sustain gameplay, then port it
ok
stuff in the browser is better documented
part of me is thinking this will end up like sim earth and that that might be my subliminal inspiration. so it'll be a maybe mildly interesting simulation with borign gameplay. but i guess i'll try it out
at the very least there seem to be a ton of examples
what's the game?
a simple app for texture editing i'm working on
how simple?
the #archived-code-general answer is, don't use scroll rects
just make it page and show a loader after the next page is requested
while you load the next batch of textures
make sure to use unity web request load texture and nothing else to load images from local files, the web, etc.
the #archived-code-advanced answer is, don't use UGUI
okay, thanks. I won't the next time, but right now, the game will consist of only a few scroll rects, nothing else running or draining resources, so I should be good. The only thing, is that buttons seem to put a lot of stress on unity. I dont understand it tho, sometimes it runs smoothly sometimes it's dogshit
i think page it
can you explain what you mean by dynamically?
do you mean from files and URLs
from files
No, but they are loading on start, so that shouldn't be the problem
so is it dynamic or not
it's not from user files, just from resources
yeah, it might be not dynamic. Sorry, my coding vocabulary isn't that good
how are you loading the images?
does it have to be scroll rects?
it sounds like there is a lot wrong going on
start by paging
don't use a scroll rect
use pages
Okay, will do. Thanks
you can try the Optimized Scroll View Adapter (or whatever it's called) from the asset store
scroll rects are hard to do right
it's way too complicated for you
it's loading slowly because of a bajillion reasons
if you think it's the "buttons"
it'll tell you what the slowness is. there's a profiler
it worked very well before the buttons components
but you say buttons, do you mean, pressing the buttons?
i mean clearly then it's what you're doing when you press the button
try the profiler first and see what it tells you
no, the whole game seems very slow when i added the button components to it
you'll figure it out
okay
Scroll View are the worst! Unoptimized, laggy, bad performance, only thing I have issues with for GUI. So I would think that is the issue not the buttons, there are different, better scroll rects made by users you could try, but if you really think it's the buttons, there are different ways to do button functionality, you can make it clickable with unity's mouse interfaces, or you could use raytracing. But what I want to know is where are your buttons? Are they in the scroll rect? post a screen shot of scene and hierarchy.
@fresh basalt definitely do not try to author an alternative to Button in UGUI, and absolutely definitely do not raytrace
i won't, dont worry
usually the most expensive thing to render on UGUI is text
you'll be able to see though in the profiler
well I'm not really suggesting that, but could be used to test out things, I always use buttons, cause I never had issues, but I actually see a lot of people use raycasting and say it's more efficient. My guess would be the scroll rects cause I had issues with them in the past, nit sure why unity has not fixed them.
yeah, i read into it and as @undone coral said, scroll rects are very bad
i'll try to do it differently. Thanks though
what i dont understand, is why sometimes when i run it it works fine, sometimes its laggy as hell
in one project I had to put clickable and draggable items in a scroll rect, it was a nightmare!
did you try the profiler
sorry, no. I'll try it in a few hours. Just finishing a few side things and i'm off
I'm trying to use the following code to copy a zip file from resources to the persistent data path, but Android is giving me the error "Error libprocessgroup set_timerslack_ns write failed: Operation not permitted" ```
TextAsset t = Resources.Load("zip") as TextAsset;
string fileName = System.IO.Path.Combine(Application.persistentDataPath, "zip.7z");
File.WriteAllBytes(fileName, t.bytes);
Be sure that your read and write permissions are declared
in the Android Manifest file
{
if (Permission.HasUserAuthorizedPermission(Permission.ExternalStorageRead) &&
Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite))
{
Init("");
}
var callbacks = new PermissionCallbacks();
callbacks.PermissionGranted += Init;
Permission.RequestUserPermissions(new string[] { Permission.ExternalStorageRead, Permission.ExternalStorageWrite });
}```
I'm using that to make sure the permissions are right.
So if it was permission related the function wouldn't be called, and the error wouldn't be thrown... right?
Those are the only two references to Init.
Are you sure that app has access within the app settings?
Oh by the way, if you just put a Zip file inside Assets it will not be compiled in the APK file
It's a .bytes file. I'm not sure where in the app settings you're referring to?
I thought they took them out of app settings and moved them into Permission?
It says no permissions required.
So the permission isn't set even though I'm calling that?
Have you configured a AndroidManifest.xml file?
No, I've never done that before.
Isn't that supposed to be automatically handled by Unity?
Here is the one that I use currently
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.
That way I can get access to everything
I may have just found ity
Doing a test build now, I'll let you know.
That worked, awesome.
Good ๐
Thanks for the help, that was driving me crazy. I feel like Unity should see you request that permission and at the very least throw a warning!
what's the objective?
why would you need to do this on android
something else is going to go wrong
like on someone's device
is it to save files?
It's to unzip images into persistentdatapath.
why though
why would you have a zip of images in your game
why not just put the images in?
are you loading the images using UnityWebRequest ?
Yes.
okay
not sure this is the right channel, but does a non-development build of a game include extractable information about the absolute file paths of the original scripts or any other identifiable info about the development computer/environment/unity user account/etc.? or where might i learn more about this
i am sorry you have to support android users
I love Android.
my personal recommendation is to significantly compress the images
until it is under 150MB
since there is no conceivable experience on android that needs uncompressed or 4k image assets
Well they're only 75mb on disc, but Unity's import system sucks.
I tried every compression setting.
I couldn't get a 300kb file under 3mb.
They aren't power of two.
what are they?
you should declare images that are really sprites as Sprites
then the atlasing will deal with npot / packing for you
i think you are creating a significant headache for yourself here
My phone is 1080x2400.
i know... but you will not perceive a meaningful difference here
The images can be zoomed to more than full screen, you will see a difference.
what are they?
Jigsaw Puzzles
This seems to work perfectly so far.
yeah but ultimately, the reason google has these rules is because Android users don't have much space on their phones
It's hardly any space.
It's 75mb, no one cares about 75mb.
basically walking is supposed to start when i press w
and sprint when w + shift are being pressed
but theyre all playing without me even pressing a key help?
got it nvm
So what's weird is that i was loading 15 objects and it was very laggy, right now it seems to have stopped and i have no idea why, even when i tried loading 100+ objects, it's still running smoothly
great
okay i have a pretty big bug in my MLAGENTS setup and i'm wondering if anyone can help. essentially they are moving in ways that shouldn't be possible given their configuration etc. i've made a 2:30 video to summarize and show the problem, and i've also got a github repository with a few scripts i think might be relevant https://youtu.be/cetmi5jJwrQ
uploading so i can get help
relevant:
- the agents are moving faster than it possible given settings
- the agents to go wrong seem to always spawn touching another agent
- the agents that go wrong never recover even if they are teleported back to an open area, once they're bad they're never getting better
- this movement happens even if no brain...
i'm happy to drop the github link if someone thinks they might help
thanks for you help tho, will check the profiler later
has anyone here worked with the A* pathing project?
looking for a quick pointer on how to get my AIPath to stick to the generated grid's height
It seems like it should be possible but I havent found much about it in the documentation
any idea why im getting linker errors regarding arkit? looks like it is labeled as a dependency on the xr-plugin-management tool
Does anyone know how can it be that I am getting this errors in Unity Cloud Build?
That is a MacOS build
When I try to build locally, for Linux, there is no problem at all. It works perfectly. So I do not get where the issue is.
Sorry that's probably a better question for the mobile channel.
Mobile? how come?
I think they just saw "mac" and assumed "iOS"
Does reimporting the package fix it?
D'oh, just saw Unity Cloud Build -- my bad. So I'm guessing there's a server that generates the build. ๐ค
if you have the time im really struggling here
info in thread
Your issue seems similar to this, but that's really all these solutions say too. Remove it and reinstall it :/
https://forum.unity.com/threads/error-when-i-try-to-install-render-pipelines.534171/
Let me se...
Yeah, the problem is that locally that does not happen to me...
only in the cloud
I guess I should make a thread in the forums
I've not made any builds with UCBs, so maybe there's something missing in a build step somewhere in that setup if that's a thing? ๐ค
I'll stop making guesses though, best of luck. Let me know when you get it working ๐
Well, it change suddenly a few days ago. I did not really change anything in the pipeline
I did though, format my PC and start from zero... but I wonder how can that even be a factor
Have you tried a Clean Build (from the UnityCloud option)? sometimes that clears up issues
@hot dock Sorry, I meant my question, which I deleted because it was in the wrong channel!
@north fossil Yes I have
How and when is your EnableARKit() being called
hey guys! I am making a multiplayer game. When playing with other players, I noticed there can be some issues when the person i'm playing against has an older version of the game. because of this, I am adding a popup that blocks you from playing the game if your game is outdated. to do this, every time I push out a build, I have a variable that is my version number. then i made a website that is always running that has nothing but an <h1>VERSION NUMBER</h1> on it. what is the best way to make it so that my script checks if the version number that the current game has is the same as the version number on that website. i'm not really sure how to go about this. also if anyone has a better idea of how to check for a new version, let me know but that was the best I could come up with.
just @ me if you have an answer
How does adding "using System.Collections.Generic" give me 7 errors?
Whatever platform you're releasing is probably has a way of checking whether you have the latest version installed as well
stack overflow question https://stackoverflow.com/questions/70935841/unity-voice-input
im doing it on itch.io
do they have a way? i know that itll let you check for an update but it doesnt do it automatically that i know of. people have to go to the game settings to check for update
I have no idea
Someone already told you what th eissue is..
do you know how to have a script check a website and take that info so it can be compared to something within the script itself
UnityWebRequest
alright thank you navi ill start looking into that
idk if this is considered advanced but i'm trying to add a method call to an eventinfo and keep failing
private void DoTest()
{
EventInfo eventInfo = exposedEvents[0];
Type handlerType = eventInfo.EventHandlerType;
Action<object, int> del = HandleEvent;
MethodInfo methodInfo = del.Method;
Delegate d = Delegate.CreateDelegate(handlerType, methodInfo);
eventInfo.AddEventHandler(this, d);
}
private void HandleEvent(object sender, int obj)
{
Debug.Log(obj);
}
the event itself is just this public static event EventHandler<int> EventTriggered;
huh, I got it to work, turns out I should be using CreateDelegate with 3 inputs, second being the object reference since my method is not static.
My what?
Sorry, I was mistaken
This might sound dumb but I come from a javascript/python background so please bear with me. Is there any way to declare an untyped variable for a function? What I want to do is use this Dictionary to shuttle around data. ```
public delegate void Method(int value); // make untyped
public static Dictionary<ContextType, Method> methods = new Dictionary<ContextType, Method>()
{
{ ContextType.none, None },
{ContextType.moveInstant, MoveInstant},
{ ContextType.moveNorth, MoveNorth },
{ ContextType.moveSouth, MoveSouth },
{ ContextType.moveEast, MoveEast },
{ ContextType.moveWest, MoveWest },
{ ContextType.openDialog, OpenDialog },
{ ContextType.dialogChoice, DialogChoice },
};
private static void None(int value)
{
return;
}```
I can probably program around it by storing the data to be modified elsewhere but doing it this way would make my life alot easier.
nope, everything in C# has a type. But all types derive from object
But I would say that there's probably a better way to do what you're trying to do
which sounds very "dynamically typed language" - which C# is not
All good. Can't make an apple an orange.
hi i am using a get request to an api, its working fine on pc in the editor and with unity remote, but when built to android, i get this error: https://hatebin.com/yjqmsvtudb
i already set internet access to require. my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEngine.UI;
using System;
using System.IO;
using System.Net;
using TMPro;
public class HypixelAPI : MonoBehaviour
{
public TextMeshProUGUI ErrorTXT;
public string UUID = "Blurred";
public string key = "Blurred";
public void Start()
{
try
{
// Create a request for the URL.
WebRequest request = WebRequest.Create("https://api.hypixel.net/player?uuid=" + UUID + "&key=" + key);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get response.
WebResponse response = request.GetResponse();
// Display status.
Debug.Log(((HttpWebResponse)response).StatusDescription);
// Get stream containing content returned by server.
// The using block ensures the stream is automatically closed.
using (Stream dataStream = response.GetResponseStream())
{
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Debug.Log(responseFromServer);
}
// Close response.
response.Close();
}
catch(WebException e)
{
ErrorTXT.text = e.ToString();
}
}
// Update is called once per frame
void Update()
{
}
}
thanks for the help!
NameResolutionFailure means there was a problem with DNS
i fixed it already, the internet requirement didnt update at first
You can, if you really want to. You can either box any value into the object type which has a performance drawback, but basically bypasses the type system, you can also use C# generics to let the compiler generate all sorts of types for you, or you could use the dynamic keyword to figure out object properties at runtime, which will tell the compiler to shut up, but then throw an exception if something is not what it pretends to be at runtime. But the example code you've shown kind of looks like you want something even more specific because you want to assign an untyped method signature to a delegate and then call them. That might be possible by using runtime reflection, but honestly, it really doesn't fit the C# idioms at first glance, so better not shoehorn it.
May I suggest an alternative design? Currently you map an enum value to a method call. Each method appears to declare different parameters though. This means, there will be some sort of conditional in your code that calls those methods with the correct arguments. In C#, a common design would use polymorphism (some may call this a part of object-oriented design). Each method in your example becomes a class and they all share an abstract base class that defines a single method e.g. "PerformAction". The method receives no arguments, but instead, each class declares member variables. Now you instantiate instances of the specific classes somewhere in your code where you have all of the information and then store them in whatever way makes it convenient, e.g. map enum value to class instance of type MyAbstractBaseClass.
public abstract class GameAction
{
public abstract void Perform();
}
public class WalkAction : GameAction
{
public int direction;
public override void Perform()
{
Debug.Log("Walk towards: " + direction);
}
}
public class MyTextGame : MonoBehaviour
{
private Dictionary<int, GameAction> actions = new Dictionary<int, GameAction>();
private void Awake()
{
actions[0] = new WalkAction { direction = 42 };
}
}
why doesn't this material property block work? In awake I create a material property block and in the update I set it to that block, But it doesn't change? Any idea why? Using URP
I think this is a Unity bug. Once I select the object in the editor it changes color?
I need help. basically i have a string thats an URL, but when i copy the url in my browser, the "&" of the url is changed to "%E2%80%8B" and after the last character in the URL there is another set of characters "%E2%80%8B". when i manually type the url it stays and gives me the right result.
the URL string that changes and the manually typed URL are the same, says a Text comparer
how do i create a script that moves a object towards my mouse, and also rotates the object to my mouse. (3d) i cant find any people talking about this online. Can anyone help me with this script?
well; first you need to define what you mean by the mouse position.
mouse position is usually a screen space thing (think pixels on your screen) rather than an in-game-world thing
often you use some kind of raycast (Plane.Raycast) or (Physics.Raycast) to get a world space position that you want to use.
Which forcemode works like rigidbody.velocity?
Hi all, do you know if it's possible to show in the inspector a serialized field that comes from a parent class?
For example:
B : A
A : ScriptableObject {
public someType someField;}
If I have an instance of B, I don't see someField in its inspector.
(to be precise, it shows if someType is a simple type. But in my case I have a list of other classes)
You have to mark the class as [System.Serializable]
None, a force will always cause acceleration but may ignore mass or time
Ah right. Thanks.
I thought there was some gotcha with inheritance, but no. It was much simpler.
And does someone whether it's possible to override event functions?
Let's say I have A : ScriptableObject, and I implemented OnEnable on A.
Can I implement OnEnable on B : A ? How can I call A's base version?
make OnEnable virtual then override it in B. Then you can call base.OnEnable() to call the one from A in B
thanks. And I noticed I had them marked as private, but I'm now making them protected in A so that I can access them
Do I need to explicitly mark it with override? I don't know if override in C# works like it does in C++ or if it's mandatory
you do, you will also need to explicitly mark the base one as virtual
Yeah you need override even for overriding virtual methods
Iโm not sure how to go about this but I want my game to check a website that I created. It has nothing on it except for 1 line of text. I want my code to go in and compare the line of text on the website to a string variable thats in my game. this will be how I will check if the version of the game they are on is outdated and then I can make a popup display and all that. In short, how do I make my code check a website and compare that text to a string variable?
You need to send a HTTP GET request to the website, using UnityWebRequest, wait for the request to complete and read the data. Then, you'll have your string.
Example in there ^
Hey it's me again. I'm trying to stop applying a force when key isn't pressed, so in my situation player moves when i press the A or D key, but when i release them, they keep moving on their own until the speed reaches 0, how do i make it so that they immediately stop when key has been released. Here's the code
if (Input.GetKey(KeyCode.D))
{
playerRb.AddForce(Vector2.right * speed * Time.deltaTime, ForceMode2D.Impulse);
}
if (Input.GetKey(KeyCode.A))
{
playerRb.AddForce(Vector2.left * speed * Time.deltaTime, ForceMode2D.Impulse);
}
```
You can check with an if statement if d or a isnโt pressed and then set the velocity to 0
Also I think they are continuing to move cuz u are applying a force to them
Also not sure that question fits the channel tbh
Yea
is there any way to do it without another if statement
You can use playerRB.velocity instead of addforce
I don't think that will change anything. With the current code setup you do need another if statement to determine whether input is being applied or not
this is far from an advanced question, but you can use GetAxis to assign a value between -1 and 1 and use that to multiply your speed. When neither button is pressed it will be 0 so no force will be applied
And in that, set the velocity to 0 yourself.
Hmm yea your right
Or just donโt use if statements
Use getaxisraw
oh smart smart ty ty
And increase the rigidbody's drag so you don't get the sudden stop effect, that is very not realistic at all
my code brokey
why'd you put your code outside the method?
The if statement isnโt in update
i have brain dum b
And this isnโt really the right channel
Code needs to go inside Update
It has to be inside of update
IDE not configured
More than basic error
Posts in advanced code channel
so this
That will error, configure your IDE #854851968446365696
And yeah, go to #๐ปโcode-beginner after you configure your IDE
k
is there a way to remove all non characters/numbers/signs?
with that i mean strange characters like ZERO-WIDTH characters or similar. i have big encoding problems atm
you can do Regex.Replace(sourceString, "[^\x40-\x7F]+", ""); change the pattern to whatever character range you want to keep. this one keeps anything up from space and excludes all other non-visible and control chars
how to get this regex lib
add using System.Text.RegularExpressions;
this messes up my whole string
it is fbcfacffceceb but it should be 26807f51b5c3408fa4cff35c575ec417
Nope nope nope, if that's for removing your trailing URL-encoded data
And please stay in one channel
Hi, does anyone know a way to use the builtin 2021 object pooling for multiple prefabs (same type obvs)? My spawn rate starts slow so in the beginning the pool just keeps recycling through the same one or two objects
makes no sense to do that
you can just make another pool for the other prefabs
I thought so, but Im talking like 20+ prefabs and was wondering if there was another way
well, pools are pre-created instances, so it makes no sense to manage a random assortment of instantiated prefabs if you need a specific one
if you indeed do not care which variant you get, you can just add multiple prefabs to a generic object-typed pool
ill try that, thanks
would you mind if I dmed you if I have any questions?
Sorry, it's midnight and I'm about to log off for the night. It would also be better to keep all questions in this server, to increase visibility.
sounds good. thanks for the suggestions ill start looking into that
my cpu is 8 core 16 threads, can it run 64 jobs fully parallel?
Can anybody point me to a good resource to build a reliable ScriptableObject singleton? I've been banging my head on this one all day and still don't have something that's "reliable" enough for my needs. Specifically:
- I need to change data from the editor from lots of different code/inspectors/etc. and have that persist to Play Mode and the built game.
- Hot-reloading should "just work." This is the tricky thing, I can get this to work via Resources.FindObjectsOfTypeAll() and grabbing the old AppDomain instance, but the "working" instance then corrupts the underlying assets when I go to save them again.
- I need to lazy-initialize this data since it's used in tons of other scripts.
I'm basically building a string table, I have millions of strings that I'm trying to pre-hash and save out from the editor and load them at runtime. The strings are a significant portion of my load time and runtime.
Any suggestions?
edit: I found AssetSettingsProvider thanks to diving into the Localization package. Looks to be exactly what I'm looking for! I'll give this a go today, thanks for the suggestion @compact ingot ๐
Maybe have a look at the implementation of the localization package. What you describe sounds quite similar.
Exactly what I was hoping to hear, thanks! I'll take a look. This is so freaking touchy, I have two assets that kind of work sometimes, but one or the other ends up corrupted no matter what I do. I do have Localization on my TODO list, might as well take a stab at it now. Two birds, one stone ๐
Thanks again!
what is the gameplay purpose
what are the millions of strings? are you saying... a bunch of phrases?
why do you have text with zero width characters? where is it coming from?
the inspector would crash showing millions of strings. it'll crash showing even thousands. so that can't be right
Is there any way to tie the value being updated to a function "SetBpm(int)" or do I need a custom script for that (fetch the updated value and send to "SetBpm(int)" )?
I need help with a crate system
I have an arraylist and each element in that array has a weighting, i need to access that weighting in another script. I have multiple weightings and i need to get all of the weightings, then get a random number between 1 and all the weightings in the list combined. This will select the item selected when the crate opened. Any help please ping me or message me, and same for any questions/more details!
I have a pretty good prefab with a bunch of objects, any suggestions on how to create a "constructor" prefab?
This is a bit of an archetecture question but not sure where else to ask. I have a bunch of scriptable object skills. I am wanted to make some scriptable object characters. on these characters I want to have an array of starting skills. What would be the best way of getting all the skills in my skill folder and accessing that/ display in editor for a designer?
I ask here as I don't know where to ask:
I'm trying to optimize the game on Android devices, but I'm quite confused as I've never done it before. Besides having removed shadows (because there are no shadows at all), I came across multithreaded rendering and VSync Count. I disabled VSync Count in order to try to run the game at 60fps (I also set Application.targetFrameRate = 60). However, checking the profiler, 90% of CPU is used because of "WaitForTargetFps". I was wondering if this is a serious problem.
I read the documentation for "multithreaded rendering", but I didn't understand why it should be enabled/disabled to improve the performance.
Moreover I followed these tips: https://youtu.be/ogaWex7HzaA
They told me that WaitForTargetFps is not a problem, so I'm just wondering if multithreaded rendering should be enabled or not and why
From Unity documentation:
You should enable Multithreaded Rendering whenever possible, as it usually benefits performance greatly
That sounds like you're waiting on the GPU
well what framerate does it run at now?
is there a good reason you can't reference scenes like other assets, e.g. have a "public Scene scene1" in some monobehaviour to expose it in the inspector and then go "SceneManager.LoadScene(scene1)"? because it seems weird to be forced to create like wrapper data types and do editor scripting to get a reference to a specific scene that isn't a hand-typed int or string
there is a Scene type but it doesn't work like that
like sure the scene might then not be included in the build but you can just ... detect that and throw errors
Hi. i tried to add movement animations to my character and i made a blend tree and wtf is this :/ i think i have to make the animations loop but how? (this is my first day learning unity)
https://cdn.discordapp.com/attachments/497874004401586176/938366896569466880/prob.mp4
https://paste.ofcode.org/32cTJBjNEpxW9QP8YGvb5RG
is looping enabled in the animation clips?
hey has anyone here used NWH Vehicle Physics 2? I'm running into an issue where the wheels never want to straighten out when the steering input is between -0.04 and 0.04
i guess because the scene type is meant to be a runtime generated instance against it being something which can be serialized?
idk what are you talking about (as you know im a dumb in unity and this stuff)
you should probably head to #๐โanimation since your question isnt related to scripting
Is there a way to reference .tgz files from within the project in manifest.json and Packages-lock.json
thread or task ?
I need help with a crate system
I have an arraylist and each element in that array has a weighting, i need to access that weighting in another script. I have multiple weightings and i need to get all of the weightings, then get a random number between 1 and all the weightings in the list combined. This will select the item selected when the crate opened. Any help please ping me or message me, and same for any questions/more details!
What have you tried yet? To get the sum of all weightings a foreach loop or a LINQ call could do that. Then, it's just the random number generation, and another loop to select the item according to the weight.
There are examples online available.
What about items of the same weight?
They have an equal amount of chance of being picked, normally.
So how do you pick one?
Choose random number
Loop over list
if the item's weight is less than the random number
select that item
bail out
else
decrease the random number by the item's weight
end if
end loop
Itโs more complex than that, Iโll see if I can make a flow chart to show you the idea Iโm getting
I don't get that logic like at all
And trust me there isnโt much online around this type of code
Say you have 200 items all weighted 1, then the loop will go over all items and always just choose the final one, no?
No, because the random number will be picked from 1 to 200
From 1 to [weight sum] to be more abstract
Imaging a crate system, you open a crate and it grabs all the items in a array. All the items are different weighings. Then picks a random number between 1 and total of all weighings.
Should it be item weight <= random number?
If that doesnโt help then Iโll draw a flowchart
Not if you want 0-weighted items to count in the draw (very rare)
And why does the above logic not work for exactly this?
0 wouldnโt be possible, more like 5000 is a common item and 5 is a rare item and 1 is jackpot or something
Yeah, so my answer, as well as the plethora of online answers still stands
Trust me Iโve searched for many hours and found basically nothing apart from some if statements which I canโt use or a asset which doesnt do the job
That logic literally works lol
Yeah it does work, I've used one type I particularly liked, and took from that SO answer https://gamedev.stackexchange.com/a/162987
Pros: there are versions for multiple programming languages listed
It's a custom collection type, generic
You just have to take the logic out and adapt it
That looks great thanks! Iโll see what I can do with it!
wait actually no, that can't work right? if the first item's weight is 1, wouldn't it just return that all the time
Hi, cant find info about this problem, maybe someone knows something.
I use ScreenPointToRay func for different purposes.
Green arrow drawn in paint - cursor position.
Red sphere in scene window - raycast point from camera to cursor.
So, i aim cursor almost to left edge of game window, but Unity thinks its on opposite side. I belive it happens because i have two displays and unity uses display cursor position instead of window, and counts two displays as one. That's why 100 pixels from left edge of seconds display means to unity something like 2020 pixels from single display edge.
I get mouse position this way
var mouse = InputSystem.GetDevice<Mouse>();
var mousePosition = mouse.position.ReadValue();
How can i get mouse position on current display, instead of two concat displays
Let's get an example rolling
// Initial Set
Legendary Object, 1,
Epic Object, 2,
Rare Object, 5,
Common Object, 10
Pick a random number between 1 and weight sum (here 18): 4.
Iteration starts.
We hit the Legendary, and the condition isn't satisfied 4 > 1.
Decrease random number by Legendary's weight, we get: 3.
We hit the Epic, and the condition isn't satisfied 3 > 2.
Decrease random number by Epic's weight, we get: 1.
We hit Rare, and the condition is satisfied 1 <= 5.
Rare is picked from the set.
if the item's weight is less than the random number
this to me is weight < random, or 1 < 4 in your example
Yeah it's the inverse, I swapped the two in my original explanation
what
I said "if the weight is less than the random number" instead of "if the random number is less than the weight"
thanks for advice, it sounded just right, but unfortunately returns Vector3.Zero
oh it just sounded like you were saying it wasn't a mistake
Oh yeah I realized that sentence could be interpreted in both ways lol
So yeah, I mistakenly swapped the two operands on the condition, in my original pseudo code
var nums = new List<int> { 1, 5, 20, 50 };
var rng = new Random();
var results = new List<int>();
for (int i = 0; i < 1000000; ++i)
results.Add(getRandomNum());
foreach (var group in results.GroupBy(x => x))
Console.WriteLine($"{group.Key:00}s: {group.Count()}");
20s: 266955
50s: 666604
05s: 66441
that seems weird
int getRandomNum()
{
var rand = rng.Next(1, nums.Sum());
foreach (var num in nums)
{
if (num > rand)
return num;
rand -= num;
}
return -1;
}
Hmmm, no 1's picked in one million iterations ๐ค
Try with a lower bound of 0 for the RNG
I see now yeah, and that means the algorithm implemented in one of my programs is wrong, as the lower bound is 1 :)
Would anyone know why this does not appear to be serialized into the editor, is it because of the EventTrigger base class and some specifics of how its component renderer works? ```cs
public class MenuController : EventTrigger
{
[SerializeField] public UIDocument target;
private VisualElement rootElement;
}
I need help with import packages.
I want try https://github.com/burakoner/Tatum.Net
tatum.net needs to be installed through nuget.
I saw nuget and unity doesn't collaborate.
But then I found https://github.com/GlitchEnzo/NuGetForUnity
So I install the dll from nuget:
but now the problem
inside the tatum.net (sdk? i think it is an sdk) there is Newtonsoft.json, but it is in the Packages folder too.
Multiple precompiled assemblies with the same name Newtonsoft.Json.dll included or the current platform. Only one assembly with the same name is allowed per platform.
I have to delete one of the 2 Newtonsoft, but if i delete the one from the nuget package it will be reimported automatically.
I don't know how to delete the one from Packages folder
I exported the interested tatum dll, deleted all nuget, then imported dll. it compiles
not sure if this is the right place for this, but i'll give it a shot
hello, I have a fairly straightforward question. i'm trying to create a hierarchy of scripts that can communicate with each other for the purposes of a unity project, but can't seem to figure out how to make it all tie together. i've been using 'internal' and 'public static var' as much as it will stretch, but i feel like there's got to be something else i'm missing or not understanding. the layout i'm going for looks like this, where the lines represent which scripts can communicate w/ each other. one of the issues i'm running into is that making the scripts communicate with the 'internal' method seems to require them both being on the same object in the unity editor, and i'm not sure how to get them to communicate otherwise. here's a picture of what i want it to look like, in basic terms https://imgur.com/a/dneLjyZ. any help would be greatly appreciated.
it's really important that the scripts not connected w/ lines can't change/see each other's vars
can anyone suggest a solution?
thanks anyway xD
maybe i misunderstand, but when they inherit from the objects above, its protected what you search
Whenever I am hitting the + button on a list in editor it is copying the data from the previous entry. The expected behavior is to start clean every time. I have tried a class. A class with default values in line and through constructor, and also using a struct instead. How do I keep this from happening?
[System.Serializable]
public struct DialogResponse
{
public string label;
[TextArea(5, 5)] public string tooltip;
public List<DialogCheck> requiredChecks;
public List<DialogEffect> dialogEffects;
public SO_Dialog connectedDialog;
}```
Did you try it with the OnValidate Method or an own custom Editor Script?
I have not. It is being referenced in a normal scriptable object. [CreateAssetMenu(fileName = "New Dialog", menuName = "Scriptable Object/Dialog")] public class SO_Dialog : ScriptableObject { [TextArea(10, 10)] public string content; public List<DialogResponse> responses = new List<DialogResponse>(); }
does anyone have a solution to the question of letting scripts change each other's variables (but not letting every script) that i posted? sorry to ask twice but i tried in another channel and they didn't know
i can post it again
then you should look for an custom Editor script like
'[CustomEditor(typeof(UpdateableData))]
public class UpdateableDataEditor : Editor' and check the data there and reset it
Thanks for the help. I'll give it a whirl.
i answered you
oh... i may have been in a different channel, i'm new at discord, my fault
Yeah, in #๐ปโcode-beginner
yeah, they just told me i needed to find a solution to the question i posted xD
You shouldn't cross-post btw
Namespaces is also a way to segregate code a bit.
sorry about the cross post i didn't think anyone was here
so i do apologize but how can i see your answer? i scrolled up but don't see it
it is directly under you question
oh i see now, sorry. yes the problem is that the variables are protected between the tiers, when i need them to be able to update each other's variables, but be protected from other non-connected scripts updating/seeing the variables
is there a method to make them accesible between specific scripts?
How Can i make a damage pop up in my 3d fps game
Not specific Script but a good practice is to make them 'readonly' so just expose a Getter like, so you can control what other classes can see outside of the inherit scope
'private/protected int _classIntern;
public int Variable => _classIntern'
make a (world space) canvas, put a text component on it. make the canvas always face the camera. make a prefab out of it, spawn that prefab whenever damage is received. write your damage to the text component.
so what you're saying is that you can make certain public int's only available to specific classes?
err static int
and also if it's readonly does that mean i can't add to the variable with the 'children' scripts? basically i want one script holder to tally what the children scripts are doing, and the only method i know to do that is to have the children scripts do a myscript.var++ type thing.
Not for specific, specific is only protected(parent/childs) and internal(assembly), so if you need to access the value from other Script you should do it, like i write above. Bonus it is then also a little bit harder for Memory Cheaters
ok i really appreciate your time but i'm actually having a little bit of ahard time understanding how to actually use that information with my situation. is there something you maybe can suggest i read so i can understand how the class intern or 'getter' that you mentioned above are used? i don't want to ask for a tutorial lol
i mean from you xD
Hey all, this is a performance related question. Does anyone know how expensive it is to subscribe to an event? I'm talking in the scale of maybe 50+? I've got a class which I'll over the lifetime of the game, instantiate, and inside that class, in the constructor, I've got an event I'm subscribing to. I know without profiling its hard to judge exactly what performance implications there are but what do people think?
What kind of event
I think I have found something using your information. Thank you so much.
a C# Event public static event EventHandler<OnTimeChangedEventArgs> OnTimeChange;. This gets invoked inside the Update method of the TimeManager class. and every x amount of ticks pass by, I will invoke this. So I'm subscribing to this event from my class.
Oh yeah that's pretty cheap
https://stackoverflow.com/questions/20645033/how-much-performance-overhead-is-there-in-using-events/54566507 you should checkout this, there are also benchmarks for 1 vs 100 subscribers, maybe this helps you
Thanks guys
Hya. What is the best way to get a World position vector 3 when you have a got a transform with a position and rotation, and a vector3 offset to that position. in the transforms direction?
how to i get the world coord of a pixel?
my code:
Texture2D GenerateMaterial()
{
Texture2D texture = new Texture2D(width, height);
for(int x = 0; x < width; x++)
{
for (int y = 0; y < width; y++)
{
Color color = CalculateColor(x,y); ## the color i am calculating should not be based on a for loop but on the world position of the pixel i am trying to calculate so that the color changes when i move the mesh
texture.SetPixel(x, y, color); ## i want to know the world position of the pixel im setting for this texture
}
}
texture.Apply();
return texture;
}
I believe this is what you want https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
Also, if you are just wanting to render what the camera is rendering to a texture, look up RenderTexture and how to use them because it does exactly that.
This is a question about a state machine, it is worth noting i'm trying to use the new input system. In the 1st Image you can see the entering and exiting of a state, the Enter work perfectly fine but the Exit doesn't work at all. This 2nd image is the reason Enter works because the stateMachine uses a method call initialize which causes the playerState to enter the idle state. The 3rd image should just do the same thing as the second image except instead of just entering a state it exits the current state and enters the new one. The 4th image shows the methods the stateMachine has. Finally, the 5th image is the debug Vector2.x I get when I press my A and D keys. Any help would be greatly appreciated, however I know this is quite a big problem so I understand.
I don't know if this qualifies as a advanced question but i'm losing my mind
Not too sure where the right place is to put this. However, im trying to look at making a factory game like Infraspace, I have a general concept on the mechanics but when it comes to placing buildings on curved roads I am bamboozled. I need something that basically displays a grid on either side of the road which I can then place buildings onto. Does anyone have knowledge in this and if so could you guide me. TIA. P.s. I think this server needs a general type of chat for this stuff (or am I just being stupid lol)
So, to boil it down, when you call ChangeState, the debug for Enter() triggers, but not for Exit()?
if you comment out the middle line setting current to newstate, does the exit trigger?
(or, does the enter stop triggering)
I'm suspecting CurrentState might be null, or misreferenced, before you set it
ok sec
in the changeState method?
didn't do anything by the looks of it
but doing this //CurrentState = startingState;
fukcs enter
because of DoChecks()?
tbh im not sure how what state its in could affect enter or exit, unless its null
yeah might need to just get a fresh head thanks anyway tho
do you think its the input by chance?
let me try something
If anyone wants to take a crack at this
Hamboy Saves me perhaps...
you need to make your question more concise
The problem is the exit in the state machine wont work
but the enter does and it just doesn't make sense
To me everything looks fine, but im still new ig
might be a problem with your animator? are the transitions set up right?
Yeah I have my parameters and the transition conditions set up right
what is dochecks()
I think... xD
doesn't do anything yet but it is going to check | if(grouded) and other things like that
its like a guard clause
if the player tries to jump while in the air it will stop that from happening
Its the input system
I just did the old one and it worked
what the heck
I dont understand
this works now
but it doesn't use the new input system
I dont get why the other thing didn't work
new input system doesn't use input.getkeydown
I know
i changed it to test
but the other one was movementInput.x which is just a vector2 from the new input system
do some debugging then
I did image 5 is the debug for clikcing A and D
so if that is the case then inputMovement is not = to 0f
i mean check if movementInput.x is getting changed
ok
one moment please
I think thats what you asked for
This proves that it is working I think

Thats why its named movementInput instead of MovementInput
I can change it in ground check if you want
won't help
this won't change anything but you could subscribe your events in the script instead of the editor cs controls = new YourControlsClass(); controls.Movement.WASD.performed += context => HandlerFunction(context);
haha not a hero
Sorry How would I do this again
would that be in the inputHandler or another script?
the problem is you're not changing the LOCAL variable
do you know what that means?
It'd be in the awake() loop
You want to create an instance of your controls class at the beginning, and then when your input invokes that event, execute the subscribed function
You don't need monobehavior
oh for Awake you do
well you have a constructor
Yeah
put it in there
wait no PlayerInputHandler is a monobehavior
So thats not the problem?
isn't vector being passed a value instead of a reference
In PlayerInputHandler are you able to read the value from the context?
{
controls = new GeneratedControls();
controls.Movement.WASD.leftRight.performed += context => OnMoveInput(context);
controls.Movement.WASD.Up.performed += context => OnJumpInput(context);
}
public void OnMoveInput(...context){}
public void OnJumpInputInput(...context){}``` My only suggestion was something like this
I think I'm going to just use the old input system this is too much of a hassle holy
I appreciate all the help tho seriously
you can use the new input system easily like you would the old input. there is a doc online
@fervent silo start with this maybe https://docs.unity3d.com/Packages/com.unity.inputsystem@1.3/manual/Migration.html
just so it stays familiar to you
It just wont work tho and we confirmed its not the state machine. We think its because the local variable is not being updated
right...
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
it's the last answer
do you know how to turn your pixel coordinate in the texture to a UV coordinate?
i'm really struggling to think of any cases you'd use this for, it would help to know your situation. either that or i'm just missing the obvious, and in that case you can just ignore me
I tend to use polling in the new input system wrapped around with my own Input Manager, instead of the unity one.
bool res = Keyboard.current[Key.W].isPressed; // equivalent to GetKey
bool res = Keyboard.currrnt[Key.W].wasPressedThisFrame; // equivalent to GetKeyDown
movementInput => player.InputHandler.MovementInput
this is a getter to re route your variable to some other script
you can make movementInput as abstract in PlayerState class
hiiiii i have a performence problem, i use a split screen with 16 cameras but for the same thing
Do you know if this is possible to use and repeat only one camera ? because i have 3fps on my phone..
Sure, render the camera to a render texture and use 16 RawImage UI elements drawing that texture
So I have to hold a huge amount of data in memory. Right now its held in queues of classes with some inheritance.
I'm building for WebGL which online states that you shouldnt exceed 2gbs of memory. And sure enough if I go beyond that it really starts to chug the application.
Is there anything I can do to improve the memory footprint in webgl?
I have to keep track of the position of each entity in the scene every second for 10 minutes
Why? Surely there's some opportunity for compression
Can't the oldest data go into a slower storage medium
What options do I have in WebGL for slower storage?
And get streamed into memory as needed
I believe you can write and read to the filesystem
In WebGL? Woah thats news to me
Looks like you can use external calls to javascript
You can also call JS functions from unity code
Yeah
So you have all the normal JS options
Interesting. Thanks for the info
@tawdry perch Basic functions of File.IO are implemented on WebGL.
The only thing you need to do in JS is to tell the browser's virtual filesystem to actually write to disk
I thought web browsers wouldnt allow you to write to disk at all. Still looking into that, but thanks. I'll stick to using C# when possible then
well they don't
but they let you write to internal storage systems which work just as well for most purposes
what is the game
or is it "a visualization"
Can't really discuss it here unfortunately, sorry
sounds like it's a visualization
are you using DOTS?
No, would that have helped?
no but the choice of the word entity is unusual
if you're not using DOTS
and the use of queues... you can't really make like, a network data visualization using unity webgl
Hmm.. yea I guess. I use that word a lot generally
are you trying to do something that grafana would typically do?
or visualizing logs?
Yea I cant really go into it like I said
okay it sounds like it's a networking or maybe audio visualization
kind of the same thing in principle
and maybe the inheritance is the different types of network events.
from a conceptual point of view, there's no point in storing more data than you can physically represent on screen. i believe this is the #1 most common error in developing systems like this. you have X*Y pixels and maybe Z discernible colors for those pixels
which is considerably less than 2GB
Anyone have experience with ghost collisions? I'm attempting to make a modular game where the user can create levels. However when I place two planes exactly next to each other and I roll a rigidbody sphere over the edge where they connect a ghost collision sometimes occurs and sends the sphere up into the air. I've seen Havok physics can help with this, but I'd rather not switch to DOTS yet until it is production ready.
so if you're say, doing something something prometheus (where else would 10 minutes come from? maybe polling sensors or somethinng)
i guess i don't know why the webgl application would be scraping that, but it sounds like that's what you're doing
if you're visualizing a point cloud, you probably need a dedicated application for that
like if this is LIDAR sensors or something
or some kind of photogrammetry dataset
it's pretty hopeless to try to do that in unity
but let's go with network events, because you said queues and inheritance and there are extremely few situations where you'd need to do that
the amount of information in a histogram or a time series at the moment it's actually rendered is extremely small
it's certainly less than the number of bytes in the image used to render it
maybe you're connecting directly to influx or cassandra or something... this would be a mistake
@tawdry perch so at least conceptually, if you want to visualize something, you still need an intermediary program to aggregate the data for you into something that is at least less than the amount of pixels you have on screen
engineering wise, if you want to take advantage of a game engine, you probably want ot explore something like VFX Graph
which i don't think works in webgl... which should signal to you that this is going to be very difficult
I love this speculation lol
I'm pretty confident in the implementation for our use case. I have a solution already tho based on some reading you guys pointed me too
well surely it wouldn't be a game
Yea its not really a game
so right off the bat, i'd say you're making a mistake
and your confidence is misplaced
it sounds like you have something that doesn't start in the browser, practically, in any place it's valuable to have webgl, especially not on mobile devices
You should write a book.
Yea I pushed back on it being webgl but its a strict requirement.
Thankfully, I'm a pretty good web engineer so I can make it work ๐
this is coming from someone who's deployed webgl unity games
i can only speak from my experience
i think you shouldn't build this in unity. i think you should stick to d3 or whatever
I haven't personally had issues with this, but this is a known issue. I've seen someone attempt to fix this using the new physics contacts modification API:
https://forum.unity.com/threads/experimental-contacts-modification-api.924809/#post-6482950
I hear ya, and I appreciate all the info and speculation. The issue isn't really the rendering. Its the data footprint. It goes beyond screen space unfortunately. Its more like raw data thats tracked
Unity's performance has been fine in rendering
it's not possible to shove a lot of data into the browser