#archived-code-general
1 messages · Page 185 of 1
public enum MyEnum {
Foo = 1,
Bar = 2,
Baz = 4,
Buz = 8
}
In binary, a power of two is all zeroes, except for a single 1 somewhere
So Bar | Buz is 0010 | 0100, which is 0110
0110 is binary for the number 6
Note that there is no enum value with a value of 6
So, by default, you wouldn't see Bar, Buz or something
it'd just show up as an unknown enum value
The [Flags] attribute tells C# that you're combining enum values like this
When Unity sees an enum with that attribute, it gets displayed with that multi-select dropdown
rather than the default, which only lets you pick one enum value
You may find examples that use bitshift too (1 << N, with N ranging from 0 to 31 i think). It's just another way to put the power of 2.
https://unity.huh.how/info/bitmasks here's an example
correct -- you can construct a layermask from a layer ID this way
1 << id is a power of 2
1 << 0 == 1
1 << 1 == 2
1 << 2 == 4
etc.
int is a 32-bit number, so you can hold 32 different powers of two
(well, one will be a negative number, but whatever)
so, tl;dr, you should do two things here
- assign a power of two to each enum value
- use the
[System.Flags]attribute
And if you want to manually add an "everything" enum, you could indeed do something like ~0
There will be an "Everything" option in the inspector if you serialize a field of that enum type
But you might want to be able to do that from code, too
var noFooPlease = MyEnum.Everything & ~MyEnum.Foo;
Understood, thanks a lot
What's the easiest way to poll the actions using the new input system?
I tried doing this ```cs
//INPUT CONTROLS
public PlayerInputActions _playerControlls;
public InputAction _attack;
public InputAction _jump;
public InputAction _interact;
public InputAction _dodge;
public InputAction _stomp;
public InputAction _kick;
private void Awake()
{
_playerControlls = new PlayerInputActions();
}
private void OnEnable()
{
_attack = _playerControlls.PlayerMap.Attack;
_attack.Enable();
_jump = _playerControlls.PlayerMap.Jump;
_jump.Enable();
}
private void OnDisable()
{
_attack.Disable();
_jump.Disable();
}```
But all it does is creates this list of actions on my script.
I assumed it would use the already predefined actions in the input actions list.
If I have objects Parent and its child Child, both have colliders and both have scripts that detect collisions, but only parent has a rigidbody, why do collisions from both colliders go to the script on Parent, instead of the collisions on the collider of the Parent object going to Parent, and collisions on the collider of the Child object going to Child?
Input system is more event-oriented than polling-oriented. Add an event handler to your action to receive input:
_controls.Player.Jump.performed += OnJump;
// ... in the same class...
void OnJump(InputAction.CallbackContext context)
{
Debug.Log("Received jump input");
}
You can even get values out of the context if you need to read say a vector value for mouse input or WASD movement
_moveVector = context.ReadValue<Vector2>();
InputAction is a literal definition of an input action
You probably wanted an InputActionReference
This allows you to reference an input action from an input action asset
How do I align this to left? There should be no spaces
public override void OnInspectorGUI()
{
StretchablePanel script = (StretchablePanel)target;
EditorGUILayout.BeginHorizontal();
EditorGUIUtility.labelWidth = 50f;
script.topStretch = EditorGUILayout.Toggle("Top", script.topStretch);
script.bottomStretch = EditorGUILayout.Toggle("Bottom", script.bottomStretch);
script.leftStretch = EditorGUILayout.Toggle("Left", script.leftStretch);
script.rightStretch = EditorGUILayout.Toggle("Right", script.rightStretch);
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
//DrawDefaultInspector();
if (GUI.changed)
EditorUtility.SetDirty(script);
}
e.g.:
[SerializeField] InputActionReference moveAction;
then, in OnEnable
moveAction.action.performed += DoTheMove;
where we defined DoTheMove as
void DoTheMove(InputAction.CallbackContext context) { }
If nothing actually enables that action, then you'd also want to enable it with moveAction.action.Enable();
In my game, I have a class whose sole job is to turn input action maps on and off
when you open the menu, it turns off the "gameplay" action map, for example
The PlayerInput component can also automatically do this for you. It will enable a single input action map automatically.
I'm trying to build a state system for character behavior, so using "OnJump" just adds more steps. I want to poll input directly in the switches.
Ah, yes, that's how you would poll the action
along with ReadValue to read the value if it's that kind of action
How can i make something like this or simlier to it
https://twitter.com/i/status/1680169229096476674
**This is the video showing the game main mechanic, The Player control the Character 1 (Angel) move to the door, Then replay (the same moves that player gave to the game (inputs) ), Now the player control Character 2 (devil) trying to kill the Character 1 (angel)
How can i save and replay the same Characters states on the game
**
For this #screenshotsaturday here's a simple trailer for my #gmtk2023 entry UVSU!
Do you understand what's going on in the game?
✨️I'm working on an expanded version of it, wishlist on Steam below! ✨️
410
I was using this, but didn't seem to work.
Is the action enabled?
It's in the code I linked above. It should be
i would have player input come from a component that can either directly read inputs or replay a list of recorded inputs
so if you use a Vector2 move input and a button to jump, the list would store the move input at every tick, as well as whether or not you hit jump
note that this would require some determinism
a change in framerate could screw everything up
It's like how Trackmania does it yeah, it replays input, instead of repositioning
you could handle input and movement in FixedUpdate
But yeah you cannot have randomness in the input processing in this case
Does TransformPoint/InverseTranformPoint use sqrt? Can't seem to find anything in the API.
but you'd have to watch out for problems that come from doing this, like missing an input because your framerate is way higher than the fixed update rate
I don't think so - but why do you ask?
presumably it's just some matrix multiplication
Source not available - it's extern so done on the C++ side
As long as you record the values you actually used to control the player, it should be ok
But yeah it would multiply the position with a matrix to transform to world space, and back to local space
Well, 1. I just like to know more about the function if I'm using it a lot and 2. this gives me a little more hope that I can solve one of my other problems without sqrt
Matrix multiplication does not involve square roots
What's the other problem and why are you afraid of sqrt
I added debugging log, doesn't seem to trigger for some reason.
that means the code isn't running
so add more logs and find out why
sqrt is slow, and if I were to use it in my code then it would be ran a minimum of 100 times
due to loops
i think you should be more worried about the matrix math...
in 1 frame
the matrix math is almost certainly more expensive
it's many multiplication operations
That's not a lot, 100 times per frame
I know why, I'm trying to fix that why right now.
I thought you meant more like 10k
guess what the entire transform system is doing constantly?

Yeah, but I'm trying to keep it lower as there is a really demanding function hapening on the same frame
This is really not something you should be thinking about much unless/until you've profiled the game and found that sqrt is a bottleneck
i would start by trying to use the actions stored on that generated class
instead of the ones you copied into the input action field
Optimize the really demending function then, not something else entirely
Spin up the profiler and see what uses the most resources
optimization is not when you minimize the number of square roots
It would be part of it
is it not what I'm doing?
use the profiler to identify hot spots. work on those
Did you check that "Generate C# Class" option?
I generated the class using this list
right
PlayerInputActions
it contains all of your input actions, and I'm pretty sure it also enables them for you
So I don't need to enable them manually?
my suggestion is to just log _playerControlls.PlayerMap.Jump.IsPressed()
I don't use the "generate C# class" option myself, so I'm a little unfamiliar
I see. I'll try that
How can i do that
maby
I'm a little fuzzy on how things get mapped from individual input sources to different input actions
I wonder if the original Jump action is getting the inputs, and your new copy isn't
I will be sure to watch out Thanks
Usually when you tick the Generate class option, you create a new YourInputAsset(), enable it (or part of it), and subscribe to the events. All of it in the code, no drag-drop required
Thanks i will use FixedUpdate
I need to find out how to reference the original
the controls for WASD movement work fine using the original, non-polling method
Would taking Input from the player in FixedUpdate be considered bad practice?
I just know that fixed update should be left for physics stuff
It straight up wouldn't work in some cases
oh
As FixedUpdate runs on a different interval, you can have skips in input especially when you use GetKeyDown or WasPressedThisFrame
How can i be sure that i did it right and do you recommend a course or tutorial?
Because the timing not "aligned" with Update
By the time you pressed the key, the frame could have ended before FixedUpdate gets run, swallowing the input you made
Yeah, you shouldn't actually read the inputs there
My thought is to read them in Update, and then apply them in FixedUpdate
Then just record the values you applied in each FixedUpdate cycle.
Then, to replay the player's actions, just consult that list in FixedUpdate
So you wouldn't actually record the player's inputs, per se
but rather than values you got based on the player's inputs
(this is very common for physics-based movement)
public struct InputFrame {
public Vector2 move;
public bool jump;
public bool shoot;
}
you'd record something like this
Does anyone here know how to set up IK for a rigged arm? I’ve tried so many tutorials and they all don’t make sense. I don’t know what poles and homes are or how to set them up. I have a rigged model all ready so if anyone can help, I’d be very thankful
Is it possible to copy a component from one game object and add that to another game object?
Can you be a little more specific?
you can serialize it and deserialize over new one
True
I want to add a trail renderer to a player without modify settings one by one
make it a prefab, attach a clone
If it’s a set value, a prefab would keep it
However, if it’s a reference to a UI element or some gameobjects, they will not
But yes. .cache is right
But that component only should exists when the player enters an area, I want to dynamically add and remove it.
which will do the copying for you
use a gameobject as a container for your component
even if its a single component, its fine
I don’t think you can remove components with code. If that is what you’re trying to say. You can disable one though
Oh. I didn’t know that
problem is recreating it afterwards
Lol. Thank you
By the way, would you per-chance have the knowledge to set up IK? It is so confusing for me.
barely touched mecanim ik, barely touched new rigging package
you have better luck in specialized channels
Aah ok. Thank you so much. I didn’t know where to look
Hello, can anyone advice me how can I make my cylinder rotate depending on the terrain under it?
I tried to do this through the Raycasting down from the center of object, but it didn't work well, as while cylinder was near some terrain's roughness it was starting to rapidly rotate (because raycast takes not the nearest point of the terrain - screenshot should explain my idea here). So I tried to do that calculating the closest point, but it still doesn't work quite well, as you can see from the video
This is a DOTS project and I am not sure I can ask this question here, but there was no help from the #1062393052863414313 , so maybe I can ask for help here. If I still cannot, I am sorry for offtop in this channel
it looks like your raycast is just going to the wrong place entirely
it may be starting underground
Are you about the video?
Yes. The video shows the cylinder mostly just standing straight up.
There is no usual Raycast. In the video CalculateDistance is used, which is calculating the closest point of terrain to the given
If I am not mistaken I CalculateDistance (or Raycast in the first try) from the center of the bottom of the cylinder: it is 2 units high, and I CalculateDistance (Raycast) from the cylinderTransform.position.y - 1f with unchanged x and z coordinates
Script also puts the cylinder.y to the RaycastHit.position.y + 1
ah, I see
So the idea is to make cylinder stand on the terrain without gravity simulation (which is not needed)
You can just do several raycasts to get an average surface normal.
afaik terrain api has a method that returns you interpolated normal of "curvature"
that too -- I have never used it, but you should be able to ask it what the normal is
smearing that out over a few points will give you something less wobbly
Okay, I will try to get use of it. Thanks
so this is my player movement script right now, and it has the problem of moving faster when moving diagonally
anybody have a recommendation for a better movement script?
Vector3.ClampMagnitude is your friend
or Vector2, in this case
this shows the problem. it suggests normalizing the vector, which is also fine, although it'll mean you can't move slowly with a joystick
it is possible to disable all mouse interactions for all scripts except of current?
I want mouse not to interact with my own scripts and UI Scrollbars when I am stretching my panel with StretchablePanel script using mouse
Unfortunately due to the process of translating terrain to the Entity, I can only use collider of that terrain. So terrainData property is not available :(
i wonder if you could just precompute a smoothed normal map
i use a hacky way of just moving around a rect transform that blocks all events
you'd make a 1024x1024 array of vectors, basically
I am sorry, I don't understand it, could you explain what it means?
transform.SetSiblingIndex(stretchablePanel.GetSiblingIndex()-1)
a transparent Image, that blocks all raycasts
it's not full screen
maybe I have to spawn transparent image under stretchablePanel?
Hm, that sounds not so bad. Thanks for the idea
But I will try to look a little more for other options
Anyway thank you very much
no more elegant options?
i can imagine you could - control all canvases raycast state
use/add EventSystem isolation contexts
I don't know what that is, but sounds like something that can destroy my game's performance
i dont see anything of sorts in event system from a glance
but adding something like that should be trivial
i dont see how it should tank performance
is this an xyproblem maybe?
no ?
so do you mean to create a list of references to raycastTarget bools and control them using a method?
what about designing around a event system current object check?
a custom class that inherits from event system?
you can directly modify event system if you drop it into the project
ugui is opensource
oh, didn't know it
something like "if object is not part of the root set as isolation context, return"
it may be much simpler than that, i didnt delve into source
I have InputSystemUIInputModule...
oh, I have found it
I wonder why it's all grey
also I cannot edit it
Quick question... I have a script that generates noisemaps from a scriptable object. I'd like to bake these prior to runtime. Is there a system that I can leverage in unity to do this--or would I just be writing a on serialization hook to create an asset file?
You can save these maps as textures
Ok I understand your point and I respect your opinion, but I disagree with you, I have bought several assets and you are right that if some assets are not of good quality, but most of the assets are of very good quality, renowned games have used assets from Unity Asset Store, I consider it a good solution and it depends on the user if it suits their needs or not.
To be honest, some of the assets that I am currently using have saved me months of work because they simplify a complex task, then I have entered to see how its code is structured and it is more than enough to understand how the tool works and to be able to extend it to my liking .
Although from the beginning what I really wanted to know was which of the two assets that I mentioned could be more useful for my type of project, I appreciate your analysis of the asset store, but I will continue buying and supporting people who really help other developers to make your job more efficient. I myself have created tools for other languages in which I am a senior and have helped many people.
Right--I guess I'm wondering where the appropriate place to put that code would be. I could use ISerializationCallbackReceiver.OnBeforeSerialize() to bake. But I'd also want to find a solution to detect if the asset changed, so I'm not redundantly baking.
I'm wondering if there is some sort of prebuilt system for a baking step in Unity that I should be leveraging?
NodeCanvas is a good starting point, well maintained for a long time. It’s primarily worth it for the great UX vs other assets. But you might outgrow it if you have non-generic needs. Once you figure them out, NC will have given you a good understanding what you need to be different.
Most of the behavior assets in the store have missed (or never taken) the train that marries FSMs and BehaviorTrees, which is a necessary evolution for managing complexity. FSMs are great for transitions/cancellations/fallbacks, BTs for describing what happens over time.
Whichever path one takes, diy or library, good (practical) AI architecture takes a few iterations to get it right in your head.
how about AssetsModifiedProcessor? you can listen for your source asset to change then rebake the texture
@thick terrace This looks like it has potential--thank you!
someone clarify
does it fully run the addnewstagepart code?
before moving onto the next method
or it will call that first method, and then move to next line, and call that one too
It will fully run AddNewStagePart--unless AddNewStagePart is a coroutine
ok thanks
test it with Debug.Log 😉
Hey guys! I recently exported my game to Webgl, which works fine in the unity editor, and, when I load in to my scene, all I see is pink.
The console says that it couldn't find the shaded Unlit/Texture and that shader is null. What do I do?
Hi guys! I'm trying to apply a velocity to my bullet, but I can't understand how it works... Could someone explain to me? Thanks! 😄
My code:
bullet.GetComponent<Rigidbody>().velocity = Quaternion.AngleAxis(Random.Range(-3, 3), Vector3.up) * cam.transform.rotation.eulerAngles * bulletSpeed;
private (Transform transform, int siblingIndex) activeUI;
//
Destroy(activeUI.transform.gameObject);
does it work this way or is it just a copy?
Should work if you add .Item1. like this:
activeUI.Item1.transform.gameObject;
although that's a value type tuple you're making with the ()s
it doesn't have Item1
Item1 is renamed to transform
and Item2 to siblingIndex
my bad, yea i works
?
TIL you can rename Item1 and Item2
yeah that will work and since its a value tuple everytime you reassing it, its a copy
doesn't copy the gameobject tho, the copy of the tuple still has a reference to the same gameobject
wait, you say it's a copy, so it won't destroy the original gameObject
it will
^
it coppies the reference
still points to the original game object
gameobject is a reference type the varaible for one, is just a pointer
a copy of a pointer, still points to the same object
also AFAIK it only copies the tuple if you pass it as a variable, they're passing the referenced gameobject
though if you are using these same 2 types grouped togeather often
i would be tempted to just write a named struct type for it
yeah it only works with the () syntax but you can provide names
Anyone ever have this issue?
awesome
yes, you're right, it works like you have said
thank u
yeah because GameObject its a reference type
anything that is a class is a reference type
primitives except for string and structs are value types
oh, my bad, I have folgot that it doesn't depend on tuple
so if it was a struct, it wouldn't work
well you're setting the velocity, not adding. But
Quaternion.AngleAxis(x, y) creates a rotation x angles around y axis, so you're rotating randomly between -3 and 3 around the Vector3.up axis.
then you're multiplying that quaternion by a vector which is the angles of the camera's rotation, which rotates that vector (not entirely sure why you're doing this, idk if that leads to a desired result)
then you're multiplying that vector by a presumably float that represents a speed
would still work if its a struct
no?
struct isn't a reference type
it's a value type
no, I mean if I had a struct instead of the GameObject
oh yeah then you would jsut have a new copy of that struct
I have messed up with a value and reference types even though I knew it
unless you can pass with the ref or in keyword
I forgot that if tuple is a value type, it doesn't matter mean it stores copies of classes
it means tuple itself is a value type
good example of those behaviour is Vector3 if you do a.position = b.position assuming a and b are transforms. you are not making them both the exact same vector but just making a's position a copy of b's position
also the tuple itself will only copy if you try to assign another variable to that same tuple, such as passing it to a method
Does anybody know what is the correct way to make an android game automatically goes to pause screen when leaving the game in background then going back to it?
yes, that explains the difference between a class and a struct
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnApplicationFocus.html
Does this work for android?
like a reference is just a address really, like the address of my house is 42, say someone copies that number down somewhere else, well it still equals 42 and you could find my house with it
you can try setting the compression format to Disabled. Don't know if it will fix that problem but it fixes some other problems so worth a try.
in the player settings
Can someone please explain how Unity sets the pivot to come 3d object? As I understood, I cannot change the pivot and the only way is to create an empty parent object as a new pivot? Is it true? It seems to me a little dirty, when you need to change that pivot for hundreds of such objects (units in RTS)
as far as i know thats correct
:(
Why do you need to change so many pivots?
The pivot point is set in the modelling program not in Unity
I want my units to have pivot near the terrain so it the calculations are easier
is the origin of these models not placed at the feet?
Oh, that's good. So it just imports pivot from blender for example, right?
yes
(0, 0, 0) will be the origin unless changed in your modeling program
At the moment I am using Unity`s meshes, and it is in the center of the cube/cylinder/sphere
ah, then yes
You usually want to make the model a child of something else anyway, though
Unit
- Model
- SomeOtherThing
this makes it easier to replace models down the road, for example
if you're using unity's meshes, in your unit prefab make an empty parent and position the object accordingly
Why it will be easier in this case?
well, in this case, it'll let you offset the model correctly
also make sure this is set to pivot, top left of the editor window:
or else it would still select center of the cube if set to center (default) when moving things in unity
note that this has no effect on how the game actually works. it just determines where your editor gizmo goes.
This. Still gets confusing for new people tho so i always recommend it
Understood, thanks
However one more question: if I set this to the center, then when I change the position of the child (camera for example), the position of parent (empty object just as a pivot) changes as well. Why?
Oh, maybe it is not the parent's position changes, but gizmo's position changes
But still parent's gizmo is glued to the camera from that moment for some reason. I thought it should be still in its own coordinates?
Doing an optimization and refactoring pass over a fork of an old volumetric lighting technique for the built-in RP. Saw this code in it.
material.SetInt("_SampleCount", sampleCount);
material.SetVector("_NoiseVelocity", new Vector4(noiseVelocity.x, noiseVelocity.y) * noiseScale);
material.SetVector("_NoiseData", new Vector4(noiseScale, noiseIntensity, noiseIntensityOffset));
material.SetVector("_MieG", new Vector4(1 - (mieG * mieG), 1 + (mieG * mieG), 2 * mieG, 1.0f / (4.0f * Mathf.PI)));
material.SetVector("_VolumetricLight", new Vector4(scatteringCoef, extinctionCoef, light.range, 1.0f - skyboxExtinctionCoef));
Wondering if there's a speed benefit from switching to property IDs instead of property names, or if it's not worth doing so
Select the parent object with the scene view set to Pivot, not Center
the gizmo will always be exactly at the position of the parent object
also if you change the child position and select the child, the child's pivot would be different. You need to change the parent's position and select the parent.
Clicking on the cube in the scene view would select the cube (the child), not the parent, so you'll still see the cube's pivot.
Okay, got it
But one last question, which may be a little silly: why I cannot set different settings for child and parent? For example set pivot and global for the parent, but center and local for the child (as I understand Toggle Tool Handle Rotation's choice affects not the editor's gizmo, but how it rotates the object (around the parent if local and around its own center if global))
it's just changing where the pivot is displayed to you, it's not a gameobject setting
as I said earlier, they do nothing to how the game works
But when I change global to local, it change the way it rotates the object
it changes how your editor gizmos work
yes, because you're rotating it on the global axis not the local axis
I leave mine on Pivot and Local most of the game
same
sometimes switching to Global
I do not like Center. It just confuses me most of the time
Oh, that was a mistake, sorry. Saw something that wasn't in fact
Thanks a lot
Hello can someone tell me a free way how to filter bad words in my game?
I did this at work once and we just found a dictionary of bad words and made sure we didn't include any of them.
It's going to be a poor system though that excludes things like the name "Hassan"
Turns out it's not an easy problem to solve
How do you accomplish that because I am having a hard time figuring it out.
Basically what I have going on right now is my Bootstrap scene contains a listener for when scenes are loaded:
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
if (mode == LoadSceneMode.Additive)
{
foreach (GameObject gameObject in scene.GetRootGameObjects())
{
//Debug.Log(gameObject.name);
if (gameObject.name == "xyz") do abc...
}
}
}
And from there you loop through game objects and add the required references when need be?
if(swearWordList.Contains(userWord)){ ban the user }
Our FREE API provides bad words detection in text for 25 languages. We process over a 1,000,000 images per month for FREE. We also offer the lowest cost enterprise solution in the industry.
Oh man this is a complicated problem
yeah, you can try to fix this with a whitelist, but then you just get lost in the weeds
what is new Vector3() without arguments? I'm trying to initialize a dictionary with values, but I want it to start "empty" and fill up as entities "learn" about the world. Currently I've got if _ant.Memory.nearestResource[ResourceType.Food] != null where _ant.Memory.nearestResource[ResourceType.Food] is initialized to new Vector3().
But I think it isn't working
It's just a vector with all 0s
Bleh
Gotcha
dk what you're doing but if you make it nullable it can be:
Vector3? nullableVector;
if it's a dictionary simply don't add the key until there's a value there
there's no reason to put an empty/null value in
yeah, that'll work I guess
I find ContainsKey a little ugly.
just make sure you use myDict.TryGetValue whenever you read it
don't use containsKey
use TryGetValue
Is there a reason?
TryGet is an if and a get all in one?
yes
How/why is it faster?
if (myDict.TryGetValue(key, out val)) {
val.Whatever();
}
else {
// not present
}```
it's faster because it doesn't duplicate the get operation / key check
compare this will the nullable solution:
var val = myDict[key];
if (val.HasValue) {
val.Value.Whatever();
}
else {
// not present
}```
Very similar I guess but using TryGet will be a memory savings in two ways:
- no use of memory before there's a value present
- the values will be smaller since they don't have the extra storage space associated with the nullable wrapper
Also the code is cleaner since you directly can work with the Vector3 instead of having to deal with the nullable
Just my $0.02
Yeah I agree
Next question: this dictionary, nearestResource is meant to store the Vector3 of the nearest resource, indexed by the enum ResourceType. It's possible for the nearest resource to get depleted, in which case the nearest resource of that type shouldn't exist anymore. It'd be best, then, to just delete the key/value pair instead of nulling the value?
yes
word
that's what it sounds like lol
unless you're using a nullable type
but that's just kinda... asking for a memory leak tbh
T Object The first active loaded object that matches the specified type. It returns null if no Object matches the type.
regardless of scenes?
Because I was under the impression that if I run that from a script in my main scene, I wouldn't be able to get stuff from my sub-scene(s)
be careful with the phrasing here
"subscenes" are an ECS-specific concept
you're just doing additive scene loading, right?
oops, I just meant scenes which I load additively
it searches all GameObjects in the game world, regardless of scene
notice it's just a static method - The call is not actually associated with any particular object
then yes, it searches everywhere
this came up yesterday
you might get punked if you run it before the other scenes finish loading
hey, small problem: I need to figure out the yaw and pitch that would give me a certain look vector
But if I listen to SceneManager.sceneLoaded and run it there, it ensures that the scene in question is loaded I assume?
another way you could do it is that every time a scene is loaded call a static event and pass itself into the event. All scene managers could subscribe to the event in awake and receive the global manager.
Not sure when the scene loaded callback is called in relation to the awake/start methods however.
I guess I should project the vector onto two planes and calculate the angle between them and...
hm
yaw seems obvious: project onto the XZ plane and then get the signed angle between it and Vector3.forward
Yet another way to do it is to make the global manager a singleton and just reference the static instance in your scene managers
Something like:
float pitch = Vector3.SignedAngle(Vector3.forward, lookVector, Vector3.right);
float yaw = Vector3.SignedAngle(Vector3.forward, lookVector, Vector3.up);```?
gah, internet died
Went that be too high? The yaw angle will be increased by the pitch
not sure I follow
SignedAngle uses an axis parameter and the vectors are basically projected on that plane
Oh, they do get projected?
that's what I was going for
should work then
The angle returned is the angle of rotation from the first vector to the second, when treating these first two vector inputs as directions. These two vectors also define the plane of rotation, meaning they are parallel to the plane. This means the axis of rotation around which the angle is calculated is the cross product of the first and second vectors (and not the 3rd "axis" parameter).
dunno
You might need to change the axis for your pitch calculation based on the yaw though
e.g.
float yaw = Vector3.SignedAngle(Vector3.forward, lookVector, Vector3.up);
float pitch = Vector3.SignedAngle(Quaternion.AngleAxis(yaw, Vector3.up) * Vector3.forward, lookVector, Quaternion.AngleAxis(yaw, Vector3.up) * Vector3.right);```
i think the axis just determines the sign
I have no idea why they changed it but the old documentation has a very nice analogy in it:
https://docs.unity3d.com/2020.2/Documentation/ScriptReference/Vector3.SignedAngle.html
If you imagine the from and to vectors as lines on a piece of paper, both originating from the same point, then the axis vector would point up out of the paper. The measured angle between the two vectors would be positive in a clockwise direction and negative in an anti-clockwise direction.
The motivation here is to get a spectator camera (which uses yaw and pitch) aligned with whatever viewpoint you had before resuming spectator mode
I got this spline, it starts of with 2 points, i get the last points REAL WORLD pos, and i add a new point to this spline, to the same world pos as the last one, so in theory the new points should always be at same place as the second point, but this does not happen, instead they somehow are getting further apart and it makes no sense?
for (int i = 0; i < sceneCreation.drawSetting.amountOfPoints; i++){
Vector3 newPointWorldPos = shapeController.transform.TransformPoint(spline.GetPosition(spline.GetPointCount() - 1));
//newPointWorldPos += new Vector3(lengthBetweenPoints, 0f, 0f);
print(newPointWorldPos);
spline.InsertPointAt(spline.GetPointCount(), newPointWorldPos);
im not adding anything to the new points position
so i dont understand why the new points would be in different places
i was struggling for several minutes with it refusing to calculate anything non-zero
...i was using the brain's transform
this:
Vector3 newPointWorldPos = shapeController.transform.TransformPoint(spline.GetPosition(spline.GetPointCount() - 1));
Implies that the positions are in local space but this:
spline.InsertPointAt(spline.GetPointCount(), newPointWorldPos); is inserting a world space position
(the brain is not the thing that rotates!)
well spline.GetPosition(spline.GetPointCount() - 1) ---> gets position of point in local space
yes
so wouldn't it follow that insertion also uses local space?
WHy would you get in local but insert a world space point?
Vector3 lastPoint = spline.GetPosition(spline.GetPointCount() - 1);
spline.InsertPointAt(spline.GetPointCount(), lastPoint);``` It should be this simple, no?
Yeah. I get the wrong yaw if I don't first project the look vector onto the XZ plane.
well because i looked at unitys code and as u saw here
they converted mouse point to world pos, and then passed it into the insertion
but that's not a position they got from the spline
in that example they're just using an object at the origin with uniform scaling so world space and local space are the same
they're sidestepping the issue
you can't sidestep the issue
i've done exactly this before :p
i am now pointing in various directions. i love vectors.
hmm im not exactly sure i get this, coz like the spline point that you get is local space, and transfrompoint should simply get the world pos of that? but what you said did fix the issue tho, thanks!
yes, because you need local space, not world space
it won't worked in that code above because world-space and local-space are equivalent if you have no parent and your transform is the default
0 position, no rotation, 1 scale
So the mouse screen position to world point was the same as the spline local space?
Yes, because the two spaces were equivalent
transform.InverseTransformPoint goes from world-space to local-space
it would be used if the spline weren't guaranteed to have a default transform
I haven't worked on a 2D project in quite some time, but I seem to remember this working? I feel like that's how I've always done it.
private void FixedUpdate()
{
Vector2 vel = rb2d.velocity;
/*rb2d.velocity =*/ Vector2.SmoothDamp(rb2d.velocity, moveVector * movementSpeed, ref vel, movementDelay, maxSpeed, Time.fixedDeltaTime);
rb2d.velocity = vel;
}
sure, that'll smooth-damp your velocity towards the desired velocity vector
oh wait, you do nothing with the result
oh I see what you did
yea, i seem to remember the ref value assigned back to the rb2d's velocity would work but it seems not
SmoothDamp takes several parameters:
- the value to go from
- the value to go to
- a ref parameter for the velocity (how quickly the value changes)
- the time taken to move
The third parameter is how quickly the value is changing
It's not the value
not the 4th value?
Forget entirely about how you're trying to mess with a rigidbody's velocity
the terms are overlapping here
currentVelocity is how quickly the smooth damp is changing your value right now
It's passed by ref so that it can be updated by the SmoothDamp method
the method returns the updated value
ohhh. Ok, in that case it should be a field value. Documentation is really not clear on that.
You're getting confused because your value is, itself, a velocity
It has memory, unlike things like Lerp and MoveTowards
yea I get it now
i feel like if the docs said "The current velocity of the function, this value is modified by the function every time you call it." or something instead of "The current velocity, this value is modified by the function every time you call it." it would be more clear.
or at least add in the description "currentVelocity should be a field value" or something. There's no example on how to use D:
isn't it right there https://docs.unity3d.com/ScriptReference/Vector3.SmoothDamp.html
smh
i submitted feedback
any freaking channel where one can ask blender related things?
there's a whole !blender discord
A supportive community for Blender artists of all levels. Share your work, ask for help, and learn from others! https://discord.com/invite/blender
yep i know, anyways ty
great! then you know where your blender related questions belong
also@heady iris another thing,
Approximately the time it will take to reach the target. A smaller value will reach the target faster.
but when 0 doesn't move? 🤔 for 4th parameter
i wouldn't be surprised if it broke
although, it looks like smoothTime is clamped from below to like 0.0001f
perhaps you mean the 5th value?
that's the maximum speed to move at
no i checked cus i thought i was changing wrong value
show your code.
seems to only happen when Time.fixedDeltaTime is supplied to it
private void FixedUpdate()
{
rb2d.velocity = Vector2.SmoothDamp(rb2d.velocity, moveVector * movementSpeed, ref moveSmoothVel, movementDelay, maxSpeed, Time.fixedDeltaTime);
}
well when i tested it maxSpeed was at 100
ah
it calculates maxSpeed * smoothTime at one point
i dunno what the rest is doing; i'm just looking at what VSCode can give me
this happens after clamping smoothTime to 0.0001f, but it still might be so small you get weird results
actually it works but it's so bizzar man. if I set max speed to 1 thousand it works
yeah, because of that clamping
sorry, 10 thousand
you can really just make maxSpeed be infinity
that's the default
float.Infinity
er
Mathf.Infinity
this value gets squared, so it might get very small
I was assuming maxSpeed was how fast the ref velocity parameter would be allowed to change
like measuring its magnitude or something
That is correct.
at least, it's the effect it has
I dunno how it interacts with the rest of the calculations exactly
so feel like it should still move even when max speed is 100 and smoothTime is 0
Thank you very much for your answer.
DO you have Collapse turned on in your console window?
that was indeed the case
i'm a little stupid
man you are crazy
you helped me like six months ago too
don't need help, just sharing the sadness
ref fields are a pretty weird thing to use
I find them useful for functional code with lots of delegates and higher order functions.
Indeed
ok, so im kinda stuck with something i cant seem to find an answer to with google, soooo, is it possible to create a undetermined amount of tmp text sprites at runtime? or some other neat way of adding them to tmp text? as im currently using 4 raw images outside of the text which are fun and all, but if the book im loading contains more then 4 images in that chapter, i cant display those.
Uhh anyone know why the ContextMenuItem doesn't work ? I literally copied it from the docs and its not appearing.. The ContextMenu does work though.
[ContextMenuItem("ResetName", nameof(ResetPlayerName))]
public string playername = "";
void ResetPlayerName()
{
playername = "";
}
[ContextMenu("SumMethod")]
void SumMethod() { }```
Is it supposed to go on the method?
there are two versions, one is for member vars
Ohhh oops.. duhh need to right click the Field that has the ContextMenuItem... Makes sense 😛
Ah yeah I assumed you'd done that in the screenshot 👍
Use this attribute to add a context menu to a field that calls a named method.
reading skill issue 😅
https://docs.unity3d.com/ScriptReference/ContextMenuItemAttribute.html
I had a problem I was stuck on for hours, I had 3 different attempted solutions and when I went to think of how to word the question I was gonna post here, I revisited one of my attempted solutions to find it worked perfectly
game dev is hard.
it's crazy how you can try to solve something, have absolutely no idea how it didn't work, and then when you try the solution again it magically works and you have no idea why it didn't work before
😶
That's outside a method
And referencing something that isn't static (positions change)
So it needs to be inside a method
You may want to do:
private Vector2 temp;
At the top, outside any method.
Then at the start of MoveBox, probably just after the if check, do:
temp = transform.position;
And I would rename that variable to like... currentPosition or something
But the box doesn't move
Completely separate issue.
You are changing Speed_Move is set after using it to add to temp.x, for one thing.
Also, both the if and else if multiply by -1. Is that intended?
What is speed_move set to? 0 times 1 or -1 is still 0
I tried making it a Multiply by , which makes the box move very fast
Is there a callback I can call for when a ScriptableObject .asset file is first created? Like MonoBehavior.Reset() ?
Maybe your looking for one of the functions under "Messages"? https://docs.unity3d.com/ScriptReference/ScriptableObject.html
Hmm yeah. It looks like ScriptableObject.Reset() works fine
Hey, I'm trying to add Acceleration and Deceleration to smooth the movement of my character, but the values are stuck on applying force to only the right side of the characters, maybe I missed something small but I can't seem to find the issue
// Update is called once per frame
void FixedUpdate()
{
if (!isAlive) { return; } // If the player is not alive, do nothing
ClimbLadder(); // Handle climbing on ladders
Die(); // Handle player death
if (!_isRolling)
{
run(); // Handle player's running
FlipSprite(); // Flip the player sprite based on movement direction
}
}
// Input handler for player movement
void OnMove(InputValue value)
{
moveInput = value.Get<Vector2>(); // Get the movement input
}
// Function to handle player movement
void run()
{
float targetSpeed = moveInput.x * _runSpeed; // Set the target speed to the constant run speed
float speedDiff = targetSpeed - rb2d.velocity.x;
float accelRate = (MathF.Abs(targetSpeed) > 0.01f) ? acceleration : decceleration;
float movement = MathF.Pow(MathF.Abs(speedDiff) * accelRate, velPower * MathF.Sign(speedDiff));
rb2d.AddForce(movement * Vector2.right);
// Check if the player is running and update the animator accordingly
bool playerHasHorizontalSpeed = Mathf.Abs(rb2d.velocity.x) > Mathf.Epsilon;
animator.SetBool("isRunning", playerHasHorizontalSpeed);
}```
public float decceleration = 7f;
public float acceleration = 7f;
public float velPower = 0.9f;
[SerializeField] float _runSpeed = 5; // Running speed```
Listen up brother. your decceleration and acceleration values are the same. What's the point of making two variables with identical values?
public float decceleration = 7f;
public float acceleration = 7f;
isn't one supposed to be negative?
or something
not sure I understand what you are doing
It's just for testing, I haven't been able to get a chance to test both values properly I've commented what the code is intended to do to make it easier to read
// Input handler for player movement
void OnMove(InputValue value)
{
moveInput = value.Get<Vector2>(); // Get the movement input
}
// Function to handle player movement
void run()
{
//calculate direction and desired velocity
float targetSpeed = moveInput.x * _runSpeed; // Set the target speed to the constant run speed
//calculate difference between current and desired velocity
float speedDiff = targetSpeed - rb2d.velocity.x;
//change accelration rate depending on situation
float accelRate = (MathF.Abs(targetSpeed) > 0.01f) ? acceleration : decceleration;
//apply acceleration to difference, then raise to a set power so acceleration increase with higher speeds
//multiples by sign to reapply direction
float movement = MathF.Pow(MathF.Abs(speedDiff) * accelRate, velPower * MathF.Sign(speedDiff));
//apply force to ridgidbody, multiplying vector2.right so only affects x axis
rb2d.AddForce(movement * Vector2.right);```
I think it's because you are using Mathf.Abs, so the values are always possitive, meaning the character will always move right
_rb.transform.position = Vector2.MoveTowards(_rb.position, _player.transform.position, _monsterSpeed * Time.deltaTime);
works fine, but replacing _rb.transform.position with rb.velocity causes some strange issues. Can anyone explain this disparity?
because it makes no sense to mix position and velocity here
they are not interchangeable
I'm a bit confused, MoveTowards returns a vector, so what makes that only applicable to position? not sure what I'm missing
vectors can represent many things
positions
velocities
euler angles
colors
you cannot simply use any vector anywhere
just like how a number can mean a weight, or an age, or an amount of time
they are not interchangeable just because they are numbers
I understand the sentiment but I don't understand how that's the case here
_player.transform.position is a position vector
_rb.velocity is a velocity vector
you cannot intermix them directly
that's all
it's that simple
you cannot simply say _rb.velocity = _player.transform.position; and expect something sensical to happen
Imagine you're cooking a cake and it says put a lot of sugar. You put a lot of salt instead and justify it with: "but they're both white crystal like powder. I don't understand what's the issue".
the result of Vector2.MoveTowards when you pass in two position vectors is also a position vector. It cannot be used as a velocity.
Of course, it's not clear exactly what code you wrote when you tried what you tried, since you didn't share it, but I'm making an educated guess here.
that puts quite a few pieces together that I was apparently missing. I never really thought they were completely separate vectors and just thought of modifying the transform directly as "teleporting" the object rather than updating the position vector
thank you for the help :)
Hey all, trying to figure out how to write this together because I'm pretty sure it can? CS f (!Mathf.Approximately(vacuumHeight, targetHeight)) { //POINT UP if (vacuumHeight > targetHeight) { vacuum.AddForce(new(0, -vacuumTurnStrength * (1.5f - Mathf.InverseLerp(startHeight + 0.9f, targetHeight, vacuumHeight)))); } //POINT DOWN else if (vacuumHeight < targetHeight) { vacuum.AddForce(new(0, vacuumTurnStrength * (1.5f - Mathf.InverseLerp(startHeight - 0.9f, targetHeight, vacuumHeight)))); } }
The code is basically the same both ways, it's just comparing two floats and inverting a couple values internally based on the difference in the floats, how do I shrink this down?
if (!Mathf.Approximately(vacuumHeight, targetHeight))
{
float dir = Mathf.Sign(targetHeight - vacuumHeight);
vacuum.AddForce(new(0, dir * vacuumTurnStrength * (1.5f - Mathf.InverseLerp(startHeight + 0.9f, targetHeight, vacuumHeight))));
}```
Something like this?
that seems correct, would just need to apply the -1 to the 0.9f
ah missed that bit
thank you, I'm gonna try it
Oh I forgot to say anything, that works perfectly, thanks!
Does anyone know of a more light-weight alternative to the LineRenderer component?
I want to draw 2D lines, no lighting or anything like that.
There's the classic GL api:
https://docs.unity3d.com/ScriptReference/GL.html
it is class
so reference
and you cannot inherit from value type (all the structs) or vice verse iirc
I see, thanks
hallo peeps, I was wondering. I have an inventory system. however I wanted a cursor to appear like a selector on the top corner of the slot when the user is using a gamepad(pretty typical i feel). Is this relatively easy utilizing the new input system, and how can I calculate the navigation without making thee slots buttons or maybe I need them to be buttons, but any advice would be great
So I think I asked the other day but didn't get a response - Unity's IAP system seems to be designed around loading products in big batches, instead of one at a time. Is there a particular reason for this? I'm refactoring some existing code somebody else made, that seems to be designed around adding products one at a time at a certain point, and I'm wondering if I need to change it so they're added before in a batch.
Does this question make sense? The code is overly complicated so I tried to only mention the relevant stuff so as to not waste time.
What does "big batches" mean? Why would you load them one at a time? You aren't likely to have more than a few dozen at most
Why can't I send my code?
the bot might be deleting it if you're just trying to paste it in here instead of using a site
is it possible to make all children images to change their alpha when parent's alpha is change?
without writing my own script
group them under a canvas and attach CanvasGroup. Use the CanvasGroup alpha
oh, works, thanks
I don't know, if it is the right place to ask. Anyways, I've got an error, when creating a 2D project from the template. The error itself coming from TestRunner module.
Library\PackageCache\com.unity.test-framework@1.1.33\UnityEditor.TestRunner\CommandLineTest\TestStarter.cs(1,1): error CS1056: Unexpected character '
Things I've already tried:
Restart Unity
Reboot
Reinstall Unity completely
Deleting library folder
Version: 2022.3.8f1, 2022.3.51f
I can't just delete Test Runner package, because 2D package depends on it.
did you edit it?
Are you able to view the TestStart.cs file?
No, I didn't
I've opened it:
Can someone tell me the version of the test runner in your project?
Maybe the 1.1.33 version is broken.
Upd: it's actually called Test Framework
Any log manager which would allow me to switch logs off per component or per gameobject or per class to reduce spam? Obviously I can comment out logs but that's not the point.
because the existing code seems to be set up that way and I need to figure out if I can afford to spend time fixing it
After some research, I've found out, that 1.3.9 is the latest version.
I've updated to it.
Now, two other files became null filled
Tried version 1.3.5 the same thing
Rolled back to 1.1.33 the same error as the first time
I can't tell if it is problem on my side, or unity forgot to bump some dependencies.
I'll try my luck with 2021 version.
I'm writing some simple AI, think like the skeleton from minecraft where it chases the player if they're too far away, and once they reach a certain threshold they start a ranged attack. How would I specify whether the player is in "chase" range, vs "attack" range? it seems intuitive to have a child gameobject with a second istrigger collider, but I think that'll require a second script to talk to the parent which seems unelegant. What do you guys do?
I just realized a state machine that checks distance each frame in the move state sounds like it’ll work fine but still curious what y’all do
Hi, can anyone advice me on how can I take input from the user in the Dedicated Server console?
So, I've tried to open the same project using 2021.3.30f1.
And it didn't work, the same error.
Creating a new project using 2021 lead to the same error.
I can open my old project just fine.
My final guess, unity forgot to update dependencies for 2D package.
@cyan compass
Sorry for the ping, can unity investigate this?
The distance check will work, but in the long run it's better to use a second collider with 'isTrigger' on, because it will consume less cpu resources.
Last time I was making an AI, I did just that.
I even have a repo:
https://github.com/R1nge/Diabloid
always nice reading through some well written code, thanks
bumping my question
I prefer to just measure distance.
I will use (trigger) colliders to detect things in the first place.
That is one area I need to profile. I'm not sure which of these is smarter:
- Just test distance against everyone
- Use a physics query to find nearby entities, then test distance against just those
Physics queries should scale better. Probably 😉
It depends on your needs.
If you have a small group of enemies, which should change state depending on the distance to the player, both will do.
But, if we are talking about 100s of enemies it can create a heavy load on the cpu, depending on the distance check formula. For example, Vector3.Distance is slower than (playerPosition - transform.position).sqrMagnetude, I could be wrong, maybe unity have optimized the distance method
Generally speaking, physics things are almost always slower than plain math.
I can't advice the best solution to you, because I don't know what type of game you are making.
GUYS I am making a multiplayer game using photon and i need help
Can you tell more about your problem?
its a top down game shooter i just want to make a gui for them
dont crosspost
stay in 1 channel
ok
multiplayer questions go in #archived-networking
I will post my question here, it might be suited better here
hey everyone, im having a problem.
I try to make a spell effect to be exactly as far as my hitbox. Lets say my Firelance should be 6 units long. But when my balancing decides to go for 7 units, i would have to redesign the effect, and that does sound annoying... is there a good way to have a Particle Effect / System or something that rescales to a single factor ?
i hope my question makes sense
what exactly about this is code quesition?
Since i assume this is something that needs to get solved on the code side of things
Im not even sure what ur asking here
sounds like you need to set parameters on your particle system through code, yes
this is more straightforward in the Visual Effect system. you'd just add a Property for the length, and use that to decide how to position the individual particles
Is there a good (and clever) way to figure out how long a particles lifetime needs to be considering the speed to fly X units ?
assuming no drag, that's straightforward
speed is distance / time
is that system available for Unity 2019.4 ?
you know distance and want time
divide the distance you want by the speed
10 meters at 5 meters per second = 2 seconds
makes sense, indeed.
A rather old version, but yes
should still do what you need, if you want to try using it
Enums are fairly useless since they don't store any data themselves and need a function to read them. Having a state as an enum is only as useful as the function checking what state there is, and this could be better done through a class as then the data and functions can be stored within it instead of creating more bloat code for reading enums correct?
But if you're already using particle systems everywhere, I would not switch just for this
eh, if I don't need a lot of extensibility, enums are fine
thanks my man. I will give it a shot!
switch statements give you very similar behavior to polymorphism: you pick the code to run based on the value of the enum (vs. the type of the object)
Currently working on a game and I've found myself using enums a few times and have noticed that each time, can you think of some good examples I can utilize them?
well, I just wrote a little debug utility that lets me place entities and give them commands
it just has a few modes
...I haven't actually put any code in there yet!
but that's how I'm going to perform actions when entering and exiting modes
i sometime use enum in ondrawgizmos to draw different things for debug
I could create an entire state machine for this
but I really don't feel like adding a bunch of classes that individually do very little
hmm, not going to lie I was hoping for someone to tell me I'm completely wrong and I was using enums incorrectly and they had much more power than I thought
they don't have magic powers
They don't have any powers haha
it's just that, for small problems, you don't need a seven layer bean dip of polymorphic abstraction
enum is just labeled values
Makes sense
Different entities can have wildly different sets of states
See I've got a really weird issue that I feel like has to be super common
If the set of states is constant, and each state is pretty small, I just write if/else chains or switches
You know games that involve a player dragging and dropping parts onto other ones that connect?
static MyEnum
{
public const int Value1 = 0;
public const int Value2 = 1;
public const int Value3 = 2;
}
int val = MyEnum.Value2;
this serves the same purpose
public const int TheNumber3 = 4;
the inevitable catastrophe 😉
I am currently trying to figure out how on earth to store this data and use it. (regarding an Attach point system) I did some brainstorming and I was really hoping for some input on how to approach this issue. could you guys help perhaps?
enum MyEnum
{
TheNumber3 = 4
}
i often use static class consists of const int since i need my enum to be array index
but extremely dangerous
i dont understand
oh, that was a bit of a tangent. it wasn't actually really relevant here...
i was thinking of when you have constants whose name is literally just the content of the constant
(you see it in CSS sometimes)
but yes, that is actually completely irrelevant. oops.
or change enum to byte which consume fewer memory
Do you guys have any idea? I've asked around a few times and even been pestering chatGBT for ages trying to get a prompt to give me some good examples of how to approach this with little luck 😦
sounds like each object should have a set of manually-authored snap points to me
Should I store those as vectors or should I just have an attached gameobject that is a attachpoint?
Transforms are nice because you can parent another object directly to them
you also get to see and move them in the editor for free
so a child gameobject right? since I have prefabs for blocks already
if you already include the case where you can have weird shapes that is not possible to automate, chances are you wont find an automatic solution
you can write a semi automatic authoring tool that setups initials
then you manually adjust after initial point gen
That would be ideal. Something that gets you a sane value would be enough.
but it still needs to be human validated
you can write validation code that notifies you of errors
That would be amazing and just what I was looking for, but I will be honest, I have not done that before, and only recently learned how to make my own enums show in the inspector through serialize field
and so on, you help yourself with things that can speed up content production, but you cant completely automate everything unless you have a very strict set of constraints
Where can I start learning?
just do stuff, start with something
How would I go about auto generating that, and aren't I unable to do that in the edit mode?
I was thinking about that a lot
welcome to the world of editor scripting (:
Play Mode and Edit Mode aren't that different
Since you need to run the game for the code to execute so how do you get it to run and still be in edit
enlighten me!!
You dont
for an intuition:
you can do everything in edit mode
Play Mode just keeps you safe
even run physics
The game is always running.
and animations
There are a few easy options too like context menu or menu item which you can run code at the click of a button.
there is no spoon
and quick question, when I build this, that code will be taken out or seperated right?
ah guys i have a question.
is it possible to create a curve between 2 objects?
i want an specific object to move along that curve for a second, but also, if possible, bent the character fitting to the curve.
editor code stays in editor
like if I adjust where an instance of a gameobject that an editor script generates in the editor, it won't be localized and reset on a build that gets published?
not sure what you mean by that
I'm finding it a bit hard to explain, let me give it another go
Bent the character?
As for your first question, a slerp may be enough for your case or look online for custom slerp/lerps.
So lets say we make this script that will automatically place some attachpoints where it thinks they go, and then once it does that I decide that one of them is good, but lets say another isn't good and I remove or move it slightly, will I be able to keep these changes when I go into play mode? since usually play mode executes a bunch of scripts over again, it wouldn't reset the position of the object I decided I wanted to manipulate?
you will be manipulating data in the asset directly
same way you manipulate prefabs in editor
data is serialized into the object you are editing
which is then used in playmode
lets get to the point, i want to create something like the mario odyssey capturing animation
I think I understand, but this a bit confusing and also really interesting and I tend to find I learn best by doing, do you know if there's a example github of a concept like what you are talking about?
the editor scripts would modify your game data.
On mobile so can you just describe with words lol
their job is now done
or could you help me create a very simple version and I can go from there
There really isnt much of a concept to even describe. The goal is literally just to have the editor place objects around, it's the exact same as if you wouldve placed them. They'll be saved and usable in play mode like any other object
Editor script place objects around*
but how do I even create a script for this, it's obviously not derived from monobehavoir
create a test script,
create a custom inspector for it,
add Vector3[] array to it,
in the custom inspector in OnSceneGUI, use Handles class to draw spheres that are associated with points in that array,
use Handles transform gizmo to move points around,
result is you can click, drag, delete points in that array
after that everything else will be clear
Ok, I will try that now, ill ask if I have questions
i outlined a learning path, which involves lots of reading at each step
Depending what you choose to do, yes it could be. A context menu would work on a MB
result will be you ready to tackle the custom editor for your purposes, somewhat
hey, does anyone know how i can get sharper/crisper shadows? right now they look pixelated to a degree. (3d urp, directional light)
by test script you mean just a new script, there isn't some special test class I assume
is there a risk if I dont use a new project haha
ah fair then it should be fine, mine doesnt take too long
a custom inspector would be initalized on an objec though right, not an script?
this is all I can find on unity documentation:
https://docs.unity3d.com/ScriptReference/UIElements.InspectorElement-customInspectorUssClassName.html
How can I get the velocity of a rigidbody right before a collision?
store it in a variable
stop storing when collided
Should I use FixedUpdate() in order to store the velocity?
Is OnCollisionEnter() always called after FixedUpdate()?
So it is better to store the velocity of an object relative to the object it collides with. Found some forums where people were saying the same thing. Noted with thanks!
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.
I know this is bad code but it's just some prelimary tests but I'm absolutely baffled by the logs. For some reason the logs show _timeToRemainStillAfterMoving as negative, and it's causing a lot of strange behavior. I have no idea how it's even possible to get a negative value here
I'm setting the variable equal to a random range between 2 and 3, and it somehow spits out negative
you setting it after waiting
RandomMove waits for 3 to 6 seconds before reassigning _timeToRemainStillAfterMoving
It's also getting started every single frame
you are starting a new coroutine
yes
guard it somehow, a bool or state check, ideally
ahhh I see
man that's tricky. Surprised that was so obvious for you guys to spot lol
you should abstract your states
I will, like I said I knew it was bad code, I was just confused by the logs
Pay attention to how you "guard" each part of your code.
the path taken to reach it
your condition for wandering should be "I am not wandering yet AND I'm done standing still"
what's the best way to avoid NullReferenceExceptions? Currently, I'm putting in if (_myObject != null) everywhere but that can't be correct. I think it's related to the call order: create a monobehavior > update gets called > set an attribute with a public method. And so I wind up with nulls because I think update (needing a specific attribute that hasn't been set yet) gets called maybe a frame or 2 before actually setting the attribute?
what is "set an attribute with a public method"
ofc you have to figure out the dependencies
surprisingly helpful perspective, I have a bad habit of writing logic with the assumption that specific parts of code will always only be reached under ideal conditions and it's a bad habit I need to shake
You should get a handle on the order, yes.
well it's a monobehavior, so I can't pass variables into a constructor, but I do want to set certain attributes from outsidethe monobehavior. So for example, I have like SetColony to set the _colony attribute of this monobehavior
Awake runs on every object in the scene. Start then runs before the first Update.
Awake also runs instantly on every enabled monobehaviour when you instantiate an active gameobject
so theoretically if I'm passing the objects around in start, it should be fine?
If you need to do something before the next frame, but also need to configure something first, you'll need to have an Init method that you call manually or something similar
A common strategy is to set yourself up in Awake, and to then talk to other objects in Start
called manually from Awake or Start?
Got it. I'm trying to stick to this pattern.
Neither. It would be called by whoever instantiates the object
e.g.
var thingy = Instantiate(myPrefab);
thingy.gun = someGun;
thingy.faction = Faction.Dudes;
thingy.Init();
Init could then do something with the gun and the faction
Awake runs as part of instantiation, and Start runs in the next frame
I see
I recently had a problem where my spatial audio sources could get asked to play a sound before their Start method had a chance to run
so I threw in a manual Init method
But like I've got code like that in the Start of another object
like this i mean
colliders
@heady iris you familiar with Dictionary and SortedDictionary?
ask your question
I was wondering if I should switch to using a SortedDictionary instead of a Dictionary if I don't expect to have a lot of elements in my collection.
use SortedDictionary if you need to access the dictionary's contents in key-sorted order
yea but I believe for smaller number of items SortedDictionary is faster
well, if you believe it, then go ahead and do it
i don't know the gory details of the implementations
SortedDictionary is a tree and Dictionary is a hashtable
log(n) comparisons vs. a constant-time hashing and lookup
yea ik, which means it's O(log(n))
i suppose it could be slightly faster if hashing is expensive
profile it if you think there's some kind of difference to be had
Help with a NullReferenceException
O(log(n)) could be faster for a while than O(1) depending on how fast O(1) is. I can't find any details on how fast A dictionary actually is.
search in binary tree is O(log(n)*size of key) while hashing is O(size of key)
hashing is not O(1) actually unless you pre compute the the code
which is why you'll need to profile it if you think there's going to be adifference
well, if the key is fixed in size, then the hashing is also constant-time
I'm talking about accessing it
accessing it requires hashing the key, yes
oops yea, interesting, everything I read online says it's O(1)
btw in many case i believe the code will be pre computed
It is constant-time for a fixed-size key
the O means different things in different contexts
and stored
you can find massive examples of claimed O(1) when its actually deeply not 1
its just 1 relative to other algorithms
well, O(10000000) is still O(1)
and discards details
but you can certainly get bitten by the constant
my key is a Vector2. It's hash function shouldn't take longer sometimes and less time other times, right? So it should be O(1) if it's precompiled.
yes, that's going to be constant-time
all of this is bikeshedding. just use the dang dictionary and go make your game :p
i need to run for a bit
That actually explains why it takes around 8 milliseconds for my pathfinding to work the first time then like 3 other times, bc of the JITC
unitys vector hashing is also slow
what about float2's hashing?
probably they chose the safest less collision spookyhash
or int2's hashing
i checked the method with deep profiler
the what?
vectors use spookyhash
Hi, I'm not sure if this is the right place to ask this question, but I'll give it a try.
I am currently working my way through the Open Game Project "Chop Chop" (https://github.com/UnityTechnologies/open-project-1) to learn more about Unity.
In the Initializer Scene, the LoadEventChannelSO is loaded as AssetReference Async. However, in the following scene, the PersistenceManagers scene, the LoadEventChannelSO object is referenced directly in the SceneLoader (not via AdressableScript, which would have to be loaded first).
I don't understand why. Can anyone tell me why this was done?
How can i make something follow the mouse if the mouse clicks within certain bounds, for example i want to have a system where you can view a 3d model of a gun and use the mouse to interact with it like pulling back the bolt or removing the magazine by clicking and dragging. Is there a way to do something like hitboxes or something around the separate intractable parts and say that if the mouse is over those "hitboxes" that part is interacted with?
You need to translate the mouse position into an appropriate world position
to start the interaction, you'd just raycast and see if you hit a collider on an interactable thing
currently i have something like this, when you press mouse 2 you can drag the mouse to rotate the model
for something like a bolt, you could use Plane to define a plane along which the bolt moves
and then use its Raycast method to figure out where on that 2D plane the mouse is pointing
then you'd need to decide where to put the bolt based on that
and then i think i could use Mathf.clamp to stop it going to far back or forawrd right?
sounds like something that Vector3.Project and Vector3.ProjectOnPlane could do. I'd need to think about that a bit.
You'd clamp the position, yeah.
Imagine turning a mouse position into a value between 0 and 1
0 is the bolt all the way back; 1 is the bolt all the way forward
you're find the closest point on a line to the mouse
and then figuring out how far you are along that line
not sure what the math for that would be off the top of my head..
I know I've done that math before
I guess you'll want to figure out what "kinds" of controls you'll need
certainly a 1D axis
and one for rotation around an axis
e.g. to unfold a stock
for moving a magazine around, you could do 2D movement: lock it into the plane of the firearm and move it around on there
and maybe a kind that doesn't move at all
like clicking to change the position of a safety
Hmmm, alright, i'll probably just try out some of the stuff you mentioned and mess around with scripts for a while and see what works for me
i currently have one script thats inheriting from another.
im trying to have the inhereted script execute a void inside the ones inheriting from it but it wont work.
wdym 'a void'?
yknow these guys in the code
Oh, you mean a method?
well it says void there so i didnt think there would be any communication error
void is a return type not a description of what it is
i know thats not technically what it is but i really dont think anybody else would be confused on what i was trying to talk about
not confused, just trying to educate you in correct termimology
void Awake()
is the signature of the Awake method
so i was right in that you were only acting confused so that you could correct me
correct
its ok, it was a communication error. You would say "a function" or "a method" not "a void", "a void" doesn't really make sense
he just admitted that it wasnt a communication error
no they just said they're not confused
this server is as much about education as helping, when you ask questions to get good answers using the correct terminology will help your cause
but to answer your original question
you are using the wrong access modifier which is why the inheriting class cannot see the inherited method
See what I mean about terminology?
trying to figure out walking along walls, ive almost figured it out but not competely, it rotates around the worlds z axis but not around the x axis, and im unsure how to fix this
rough outline of how it rotates around the object
heres the script aswell for all movement and rotation https://gdl.space/faxixanamo.cs
I have never used text mesh pro before and I am a huge dumb
I'm not sure I understood what the problem is and haven't looked very carefully at your code (it's loong 🥲 ) but assuming you know the normal, you can rotate the player using transform.rotation = Quaternion.LookRotation(transform.forward, normal);
That should keep the forward axis (= the z axis) of the player the same and align its up axis (= its y axis) with the normal.
I'm trying to change the text of a TMP component on awake but it's complaining the component is missing
What on Earth is going on?
using TMPro;
using UnityEngine;
public class ChangeTextOnStart : MonoBehaviour
{
TextMeshPro _textMeshPro;
void Awake()
{
_textMeshPro = GetComponent<TextMeshPro>();
_textMeshPro.text = "Hello, World!";
}
}
Do you have a TextMeshPro assigned to your object?
Be careful that there are I think 3 classes with similar names, pick the right one 😉
keep in mind that TextMeshPro is the non UI version. you can use TMP_Text for the type for either the UI version (which is actually TextMeshProUGUI) or for the 3d text version which is the one you are using
Why are they different things that's a beginner's trap
use TMP_Text if you don't care which of the two types of text mesh pro text components you are using.
because UI and non-UI rendering is completely different
OK so now that I've got that figured out, I can't get TMP to play nice with my assembly definition.
I've included them as references into the necessary script and yet it's still complaining that I don't have the right permissions to include it as a library.
remove the reference to the editor assembly there unless you want issues when you go to build. and you need to be more specific about what your actual issue is
does deep profiling affect performance if you didn't turn it off after you close the profiler?
That's the thing. I don't know how to be more specific. All I know is that I'm using assembly definitions and the code I'm using has a big squigly line under Text Mesh Pro where it doesn't elsewhere.
why not share what the error says? that would be how you can be more specific
So this script obviously doesn't work, but I'm really interested in that second line.
and does the error appear only in your IDE or do you see it in the unity console as well
also _textMesh = GetComponent<TextMesh>(); is wrong
Severity Code Description Project File Line Suppression State
Error CS0246 The type or namespace name 'TextMeshPro' could not be found (are you missing a using directive or an assembly reference?) LunaRoseManor.Spacewar.Events C:\Users\******\Working\unity-spacewar\Assets_Project\Scripts\Events\IncrementTextOnDestroy.cs 2 Active
I'm only interested in why the library isn't being included
I know how to fix everything else
again, does the error appear only in your ide or does it appear in the unity console as well
i'm not asking questions just for shits and giggles mate
I'm a big dumb
The editor shows on both the IDE and Unity
But The library isn't called "TextMeshPro", it's "TMPro"
It's a very similar issue to before where we have different names for things.
also for future reference, it's a namespace not a library
indeed: I don't think that "library" has a technical meaning in C#
https://hatebin.com/jacwzjsnps
https://hatebin.com/jzepfeqywg
Can someone take a look , I dont understand why enemy is not stopping
Note:slippery script is in the platform.
I know it doesn't matter much, but it's partially because TMP was made by some guy in a basement, and was eventually bought and added into Unity directly, and had little more than life support since. It has always been a bit of an ugly workaround for textboxes imho, but was a lot better than the standard text boxes (which Unity created about 9 years back).
There is a lot it doesn't do or does poorly that makes it awkward to work with the first time. Even RTL text, non-english character sets, etc. All unnaturally difficult to work with.
That said it's still better than the existing, and was bought and brought in. So it's kind of a messy standard - IMHO
Is it the friction on the rigidbodies?
When you say not stopping, as in not at all, or just slowly
At normal they follow me in a range
Assuming you aren't running OnTriggerEnter over and over and having a whole bunch of coroutine instances running
but I want them to stop following me for 2-3 seconds and then continue when they step on slippery platform
I meant, I don't understand what you mean. We're talking about a couple lines of code here, consisting of a dictionary basically. Why does the number of items in it matter? What are you 'loading'? Beyond that init, unless you're doing something super weird there isn't much complexity in the code itself
they continue to follow me , nothing happens when they step on the platform
I'd add at least a tag check in the OnTrigger first though or it'll error when any other trigger comes into contact with it.
Then, it also can be executed multiple times over and over. So I'd add a bool for _isRunning to prevent like 30 instances of the courotine from being triggered
I will try thanks
From there, you'll need to debug and look at if NotMoving is ever executed
using Content;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace Editor
{
[CustomEditor(typeof(Block))]
public class BlockInspector : UnityEditor.Editor
{
public override VisualElement CreateInspectorGUI()
{
// Create a new VisualElement to be the root of our inspector UI
VisualElement myInspector = new VisualElement();
// Add a simple label
myInspector.Add(new Label("This is a custom inspector"));
// Return the finished inspector UI
return myInspector;
}
}
}```
Made a custom inspector script and I have a folder path similar to this
MonoBehaviour
|
↓
Block (Abstract)
|
↓
MovementBlock
For some reason however this inspector will not show up in my project
not a code question. see the documentation pinned in #📲┃ui-ux to learn how to correctly anchor and scale your ui
I got this error in this script: Object reference not set to an instance of an object
https://hatebin.com/zqdvbfcrij
it usually helps to say where the error came from. but also you never assign to your CurrentMovement variable yet you use it in the SlideCoroutine
perhaps you want to use the enemyScript variable that is passed as a parameter to that method instead
thanks 😀
why is there no mppm documentation? it says page not found
how do i make the items in player hand visible when the correct item is in the selected hotbar slot?
i was thinking of setting it in the SO
but that wont work
https://docs-multiplayer.unity3d.com/mppm/current/about/
also there's the unity networking discord where you'd be able to ask questions about it. the link is pinned in #archived-networking
yeah that wont work
anyone please help
i've been sat at this for like half a day
if anyone can just tell me if they dealt with this
how they'd managed to get items to show
isn't that going to be a prefab you're referencing
I handled this by instantiating a prefab every time I needed to show an item in the player's hand, and then destroying it when the item was put away
you could also instantiate the item once, then just disable it when the item is put away
well, it works
as long as you don't need to remember any state that was attached to the item itself
e.g. the actual weapon shouldn't hold the ammo count if you're creating and destroying it constantly
yeah ik
(or, at least, it should not be the thing that remembers the count)
im not gonna destory them
im just gonna instantiate it
and then set it active
better performance
wait idk if its better for performance
so the SO will hold the prefab
of the item in hands?
right
if(hotbarCells[selectedCell].item && hotbarCells[selectedCell].item.itemData.handPrefab != null)
{
InventoryCell cell = hotbarCells[selectedCell];
GameObject handPrefab = Instantiate(cell.item.itemData.handPrefab, holder.transform.position, Quaternion.identity);
}```
i cant figure out how to instantiate it in the same position
like usually its here
I'm trying to prevent the below situation from causing a deadlock by making the green-circled unit start moving to the next node using the following code (my parkings on it are not exact but pretty much the situation), but it doesn't seem to work in every case. I thought I'd use the dot product between the direction of the unit's position to the current node and the direction of the unit's position to the next node, and if that's under 0, then switch to the next node if it can see it, but it doesn't seem to work. All the units are on layer 6. Is something wrong with my dot product code? This is in an update loop.
if (path.TryPeek(out next))
{
Debug.Log("Peek Success");
if (Vector2.Dot((current - rb2d.position).normalized, (next - rb2d.position).normalized) < 0)
{
Debug.Log("dot success");
if (!Physics2D.Raycast(rb2d.position, next - rb2d.position, Vector2.Distance(rb2d.position, next), ~(1 << 6), -1, 1))
{
Debug.Log("raycast success");
current = path.Pop();
}
}
}
And to add clarification to the little diagram, I tried to color-code it. The circled green unit is moving to its current node, which is the orange circled unit's last node. They are all moving in the same direction, but the green circled unit got pushed past its node so it couldn't reach it.