#archived-code-general
1 messages · Page 58 of 1
ah, should've clarified that the coroutine simply starts with teleporting the trail to the startpoint. It could just as well say trail.transform.position = Vector3.zero; or something like that.
I'd like to wait as little as possible, not even one frame if possible
Why don't you do that then.
stop emitting
Wait a frame
Teleport
Wait a frame
Start emitting
Start the animation```
that's what it's doing. The coroutine I'm referencing just teleports it to the start in the same frame it's called:
protected override IEnumerator AnimateFromTo(int index, Action<int> action)
{
Transform from = GetTransformFromIndex(index);
Transform to = GetTransformFromIndex(index, 1);
float distance = Vector3.Distance(from.position, to.position);
float fullTime = distance / speed;
float elapsedTime = 0;
while (elapsedTime < fullTime)
{
float elapsed01 = elapsedTime / fullTime;
trail.transform.position = Vector3.Lerp(from.position, to.position, elapsed01);
yield return null;
elapsedTime += Time.deltaTime;
}
trail.transform.position = to.position;
action(1);
}
private IEnumerator StupidOneFrameWaitCauseTrailRendererSucks()
{
trail.emitting = false;
yield return null;
trail.transform.position = GetTransformFromIndex(GetIndex()).position;
yield return null;
trail.emitting = true;
currentAnimation = StartCoroutine(AnimateFromTo(GetIndex(), ContinueAnimation));
}
Rewrote to this exact structure but the same thing occurs.
after some further experimenting, it seems that it's due to something else so I'm gonna keep at it for a while...
I have this simple 2D projectile gameobject.
I want to rotate it based on the direction of a vector, aligned through the tail. How do?
My ability to harness the power of Quaternions has much to be desired.
In 2D it can be as simple as assigning the direction to transform.up or transform.right
Will that condition sound.clip == musicAudioSource.clip be true if they come from different objects in different scenes, but they both come from the same asset?
Or should I compare some string related to the clip
That is a reference to the asset
As long as it's the same asset it's the same reference
I'm having a lot of trouble trying to draw a simple line between to canvas elements.. Does anyone know how I could make a line render between two UI elements like shown in this picture with the blue line?
I was able to use line renderer for 3d objects to create this in 3d very easily.. but there doesn't seem to be an equivalent to use for 2d canvas..
Alright, Thanks for theinfo
Either don't use a canvas ui for it, or implement a custom canvas line renderer.
There's also a unity ui extensions package available on GitHub. I think it has a canvas line renderer component. Google it.
Just seems wild to me that it's not part of the standard library. I think there is another layer to my issue though and that is that I have these objects nested within 2 layers of panels. It seems like Unity only keeps track of a child UI objects relative position to their parent. I suppose all that I really need is the objects position on the screen translated to world coordinates but it seems this relative position is messing up that calculation with the built in Unity functions. Is there a way around this nested UI object issue?
Not sure I understand what the issue is.
If you just need world position of an element, use transform.position🤷♂️
Running into an issue with my grounded checks and jumping in my prototype.
I was originally using the controller.isGrounded() to determine grounding, which wasn't ideal due to its' unreliability, and 'work-arounds' meaning that the player would still slowly slip off sloped surfaces.
I'm now using Raycast.Hit in the isGrounded bool. Problem is that now, it seems to be interfering with jumping, it immediately still finding that the player is grounded and preventing the jump from taking place.
I looked around online for a bit, but couldn't quite find anything to solve the issue that I'm having here. Raycast itself is incredibly short (only takes place after the soles on the character's foot and lasts for 0.01f), but it still manages to prevent jumps from happening.
Is there any way to disable the raycast checks when jumping takes place to avoid this?
UI Elements don't seem to work like that... they don't have coordinates in world space, they are all positioned relative to their parent game object on the canvas. You can see that even those these two elements are in different X,Y coordinates on the screen, their X coordinates are the same because they have the exact same X offset inside their parent panels
Of course they do. They have world space position corresponding to their position on screen.
What you see in the inspector is not world space position
It's the anchored position afaik.
Same as you don't see world position on normal transforms(you see local position)
It depends on the canvas render mode you're using. Screen space camera canvases are simpler
So these are the same two UI elements as in the previous images. You can see the two anchoredPositions here and their X coordinates are both 0 and only Y is set (I'm presuming this is the offset y-coordinate within it's parent).
Expand the "base" transform class...
Rect transform extends the regular Transform.
Any idea why my while loop would be freezing the editor?
Time.time < maxJumpTime I suppose
Tried that, though the while loop doesn't seem to trigger
Cos Time.time is not 0
When you start
The value you want to check is Time.time-startTime
oh yeah, originally it was time - startofjump
where startTime is Time.time at the frame you jumped
Time.time will always be iterating up. I think you want to capture an instant of time and compare it with the current time to see how much time has elapsed, if it that is greater than you maxJumpTime, then you could jump
you just want an if statement
Do not use a while loop unless you want the logic in it to run to completion in one frame, or are yielding inside of it somehow
so the logic is meant to make it so the player will jump higher if space is held, but if i was to use an if loop, that immediately makes the player jump higher regardless if i just tap space or not
if is not a loop
You need to change how you think about this.. remember update is running once per frame
You have a fundamental misunderstanding of how this works
You need to think about how things progress and change over time.
A while loop will run to completion in one frame. The code inside of it will be looped over continuously until the condition is false. By looped over continuously I mean the code does nothing else until it is done.
ah shit, that explains it then
Time does not advance.
Frames are not drawn
Other code does not run, etc.
Could it be run separately, say in an ienumerator?
I already have one set up to disable ground checks on jump, so yeah
Update is already a loop through, a loop that is returned to each frame. So if you just use an if statement it will check that logic each frame and perform it if it's true
oh, odd
It only ever triggers once, and that's even if the space bar is simply pressed as opposed to held over the duration of the jump (though that's likely because i haven't set up a minimum time elapsed in the conditions)
and presumably that's because Time.time becomes greater than maxJumpTime
which, if maxJumpTime is say, 2, then you have two seconds at the start of your game until you cannot jump again
It might be because it's part of a contained Jump() void, which is then executed in update when the player jumps
oh?
yeah, mine's already at a second and a half, so there's plenty of time for it to presumably run multiple times
I believe that the new Input System has a way of differentiating "Long Press" from "Short Press" and I think that is what you would want in this scenario
I haven't actually given the new input system much of a shot yet, though I could take a look at it
IIRC the old and new input systems can be used interchangably, right?
All of this can be solved with a few if statements, bools, and floats in Update
Just checked looks like they don't have a good way of handling this out of the box so you would need to do some of your own logic anyways :/ https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/Interactions.html
Ah damn, all good
Hello, is there a way not to implement every override method in the child a class, since the child only uses some of them ?
So I have an airship that I am using physics to move (so that I can have a little more of a floaty feeling). What is the best practice for handling the fact that I can't have a mesh collider w/ a rigidbody and Kinematics ?
Should I do it using a second physics scene .. do all the forces over there then translate position movements to the first scene? Or should I go with a compound mesh?
Look up abstract vs virtual methods
Helloop
Some one know why my game editor is being activated when I'm supposed to be on the game scene?
It makes the testing really difficult
And not only happens with the pause scene button
you have "Error Pause" enabled in the console window and you have errors occurring
therefore the game is pausing
Also you have disabled errors in your console log so you're not seeing them. Notice how errors are toggled off here (you have 4 errors in console in this screenshot)
Hey, so i am working on a 2d game where i've inserted different animations for different combos. I want to change the hitbox for every animation. Is there any other way to do it without having to change it frame by frame?
Note: The attack animations look similar to hollow knight's animations. It's just a white slash animation and that is the hitbox that i want to change.
(edit: Do kindly ping me when replying.)
on this though: iirc you only need 2 keyframes for resizing it
Has anyone uses the "Free Joystick Pack"?
I've been trying to flip my sprite with the joystick but I couldnt figure out how
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code*
• JetBrains Rider
• Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
It's weird, it started yesterday and is when the player jumps
is there a way to make an animation clip set a scriptable object on a script, similar to how you can make it set sprites on the sprite renderer?
Animation Event
oh yeah it can take an object, I forgot, thanks
Solved: I just put the "1" value to "0.1"
Is there a way to get a prefab from an instanced game object in code?
why would a UI question be part of code?
Oh got it thanks, sorry wasnt sure
EditorUtility.DisplayDialog... is there something like it for a windows build?
you mean a system message in windows?
I want to be able to browse for a file in the build
There are some third party plugins for that to allow filebrowsing on any platform. I think nativeshare has some option for example
There is also Runtime File Browser for free if you want to test it on asset store
oh thank you @plucky inlet
Hello !
For my last year in my school, I've got a project to do, and I wanted to recreate the Solar system with forces on Unity.
My forces are Speed and Acceleration
public double Vitesse(GameObject planet)
{
return Math.Sqrt(Constants.G * Constants.SolarMass / (Vector3.Distance(planet.transform.position, Soleil.transform.position)*10000000));
}
public double Acceleration(GameObject planet, GameObject B)
{
return Constants.G * B.GetComponent<Data>().mass / (Vector3.Distance(planet.transform.position, B.transform.position) * Vector3.Distance(planet.transform.position, B.transform.position) * 10000000);
}
and they are called in a FixedUpdate
Vector3 v = Vector3.Cross(Soleil.transform.position - transform.position, Vector3.up).normalized;
gameObject.GetComponent<Rigidbody>().velocity = (float)Vitesse(gameObject) * Speed * v;
GameObject[] items = GameObject.FindGameObjectsWithTag("SpaceItems");
foreach (GameObject item in items)
{
if (gameObject != item)
{
gameObject.GetComponent<Rigidbody>().velocity += (float)Acceleration(gameObject, item) * Speed * VectorAToB(gameObject, item);
}
}
you want the solar system, then you have to think about angular velocities
It seems to work for all my planets, they are rotating around the Sun, and seems also attracted to all planets at the same time (all the solar system is moving in my scene), but now I try to add the Moon to rotate around the Earth, and it seems that it doesn't work
Oh you are working with mass and gravity for each planet if I get this correctly?
oh really ? i've did something like that
yup exactly
with white it's better x)
than you have to alter your Vitesse function to not only take in account of your soleil origin but also the earth being its main attractor
your Soleil.transform.position is S, the sun right? but the moon does not rotate around the Sun but the Earth, right?
Physically correct the sun will still attract the moon "at some point", but for the sake of simulation, I do not think you want to calculate that too 😉
mmmh because Sun mass is >>> at Earth mass, it makes the moon goes really slow 🤔
But the moon is not big enough to be affected the same way as earth is, so the mass is a big factor of how much the moon is affected by the sun
I mean looking at it over millions of years, the moon will crash into earth probably one day 😄 but nothing you want to simulate I guess 😉
ok ok so I've maybe have a problem somewhere else in my code, because with something that makes the moon's speed affected by the Earth's mass and not the Sun as other planets, the Moon is almost motionless
Well the moon is basically travelling at the same orbit as earth does, cause the sun is of course affecting the moon. but the escape velocity is just too high to like let the moon leave earth. It eventually will one day or the "wobble" will flatten and we meet the moon here 😄 but for now you would have to guarantee, that the moon is copying the earths orbit + the earths attraction
ohhhhhhhh you gave me an idea ! I could maybe calculate the escape velocity to make that !
I'm gonna look for that, thanks a lot ! :)
Let us know how it worked out, super interesting topic 🙂
Why this works in editor, but in game it has no effect
if (Input.GetKey(KeyCode.Alpha4))
{
_input.cursorLocked = false;
_input.cursorInputForLook = false;
Debug.Log("Cursor unlocked and input for look disabled");
}
else
{
Move();
_input.cursorLocked = true;
_input.cursorInputForLook = true;
Debug.Log("Cursor locked and input for look enabled");
}
_input is script in first person asset from Unity technologies
Are you building the right scene?
not sure which channel is the best for my question:
but I am having a lot of clipping when I am using my FBX model, it is a 3D model for a real-building, so it is a bit complex, but when I navigate around it, a lot of clipping happens and it is very annoying, any ideas how to stop this?
should mention in the editor
What do you mean by "clipping"? Your character is clipping into walls or something?
no, when I navigate in the (scene) editor, around the 3D model.
You could adjust the scene camera settings.
Yes?
I tried that, but there is only the main camera, which happens when the game run, not while in editor mode.
Aight. Do you see the debugs in the console?
First, try pressing F to focus on a selected object. If that doesn't help, you can adjust the scene view camera at the top right of the scene view toolbar.
I have 2 GameObjects on the same layer. Both have a Mesh Collider but when they are on top of each other my code doesn't run.
void OnTriggerEnter(Collider col)
{
Debug.Log("it works!");
}
void OnCollisionEnter(Collision col)
{
Debug.Log("it works!");
}
currently the Is Trigger options are turned off on both mesh colliders, but if I turn them both on it still doesn't trigger the code.
@thick plume do your GameObjects have a rigidbody ?
yes
and, just to know, if you use a OnCollisionStay ?
i don't, is it a method?
same as OnCollisionEnter
i see, i don't
yeah but, idk if it's possible, but maybe when you start your scene, the GO are already in collision 🤔
shouldn't it trigger the method when i load the scene then
Yes!
idk at all :/
i see
In a build I mean.
thank you ^^
What is build?
When alpha 4 presses then those two bolean become false
You said the movement doesn't work in a build..?🤨
Or I assumed that you said that...
No, movement works but mouse cursor doesn't
In the build?
Yes
Simply
It works when at the begining I set up cursor lock true and cursor locked to true
And in opposite way
But when I want to handle that in script then 💥
Not working
I really don't understand what the issue is.
I'm also confused if we're talking about play mode or build...
Im gonna create video ok?
Ok
hello fellow unity users, ive become aware of a few different ways to do car physics, and im not sure which one to pursue, there is the sphere method, and the wheel colliders, and im sure there are many other methods.
im trying to recreate the kind of physics from Sega Rally Championship or other Rally type racing game, which one would be better for this?
This video was captured using the actual game on an actual Sega Saturn. Loading times have been removed for your consideration and enjoyment.
Where do I start? I played this game in the arcades every time I had a chance. I remember thinking while I was playing the arcade that it would have been impossible to for Sega to ever release a game like...
here is a reference for what im talking about
theres pretty much no drifting, just angling
man this takes me back..
Yeah i think NFS did the whole "drifting" thing
Another option is to also use Raycasts to kinda create suspensions
yeah, that and a few like, arcadey games
Damn, I remember that game. And some chopper rescue missions kind of game... What was it called..?🤔
unity car?
is that like
wheel colliders?
Indeed
you can get some decent results with some tweaks, also asset store has a few good Free ones
they took it down from asset store for this one
just open the project and it's the Vehicles scene
Anyone know why Unity is throwing issues related to not finding Editor assemblies during builds, despite the file being clearly located in an Editor subfolder?
Assets\3rd Party Assets\DreamOS - Complete OS UI\Editor\Scripts\InitDreamOS.cs(3,19): error CS0234: The type or namespace name 'Presets' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)
I hate this error
First you can try using namewhereitis;
Or you add assembly
Can you elaborate on this?
Script which is referenced, where it is
hey, im having a sequence container with enemies that im instantiating via addressables, the enemies are also marked as addressables, altought they aren't loaded, they just sit in that Sequence Container which is being loaded asynchronuesly. How can i release the memory that the enemy takes when the enemies dies? I guess enemy.ReleaseInstance() when he dies won't work, since I didint load him by addressables?
So the directory of the file causing the issue is Assets\3rd Party Assets\DreamOS - Complete OS UI\Editor\Scripts\. The missing namespace is Presets which is from the UnityEditor namespace.
But the point is that scripts under Assets\3rd Party Assets\DreamOS - Complete OS UI\Editor\Scripts\ aren't supposed to be compiled during builds.
Because it's inside the Editor subfolder.
Which is a special subfolder https://docs.unity3d.com/Manual/SpecialFolders.html
Idk how to solve this
anyone got a sec? My coroutine is running way too quickly, and I've got no clue how to fix this. I'm trying to make a simple disolving script, but the coroutine isn't workin as intended, and the object is just vanishing
you're gonna have to post the script.. don't ask to ask
Hi guys, I'm trying to change item scale to fit bigger character. Item has skinned mesh renderer on it. As of my understanding I need change skinned mesh renderer scale, but it doesn't work. Anybody know how to achieve that? maybe I taking wrong approach?
using System.Collections.Generic;
using UnityEngine;
public class Disolve : MonoBehaviour
{
//PARAMETERS - For Tuning, usually set in the editor.
[SerializeField]float disolveTime;
[SerializeField] Renderer rend;
Material mat;
//CACHE - References for readability and/or speed.
//STATE - Private Instance (Member) Variables
bool isDisolved = false;
// Start is called before the first frame update
void Start()
{
Application.targetFrameRate = 60;
rend = GetComponent<Renderer>();
mat = rend.material;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Alpha0) && !isDisolved)
{
StartCoroutine("DisolveStart");
}
}
IEnumerator DisolveStart()
{
float disolveValue = 0;
while (disolveValue < 1)
{
disolveValue += Time.deltaTime;
mat.SetFloat("_DisolveAmount", disolveValue);
}
yield return null;
}
}
format it properly please !code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
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.
You don't have any pauses inside the while loop so it just runs to completion in a single frame. The yield return null line should be inside the loop.
Hi guys, I'm trying to change item scale to fit bigger character. Item has skinned mesh renderer on it. As of my understanding I need change skinned mesh renderer scale, but it doesn't work. Anybody know how to achieve that? maybe I taking wrong approach?
do you mean with code?
Yes
its always got to be the easy things that confuse me aint it? lol, cheers man
Yes
I don't understand why you need to change the skinned mesh renderer instead of just scaling transforms ?
Well to be honest, I tried scaling transform as well, but it doesn't work
Well I have a character, which has script which allow to equip items on it. So script works fine, but now I have another character which is bigger. So I want to be able use same items , but scale them before equipping on bigger avatar.
It doesn't scale to the values, which was set in the Transform
quick dirty way you could maybe pass the scaling to the object once you pick it up , each char sets a diff scaling ratio mayb
What do you mean by passing scaling to the object?
how are you setting the scale in the transform?
In Edit Prefab mode just changed values
afterwards i tried to set transform on skinned mesh renderer
like this
var addedItemSkinnedMesh = partsInstance.GetComponent<SkinnedMeshRenderer>();
addedItemSkinnedMesh.transform.localScale = new Vector3(5, 5, 5);
so you have a separate prefab for large character? If not, you probably just want to leave this at one character's scale and scale it dynamically through code based on who picks it up
I'm working on a 3D pathfinding system that uses a modified version of the A* algorithm. I'm currently using a custom implementation of a Skip List for the "Open Set". Does anyone have any suggestions or resources about possible better data structures? I've tried a Priority Queue, Sorted List and Sorted Dictionary and they are all varying degrees of slower so I made this skip list but I'm not sure that it is the best option for this sort of thing.
as for your code, it looks like it should work. Maybe use a paste site to paste the whole script for context?
Yes I have another character on another prefab. Problem is with scaling, it just doesn't apply to the items
I meant item prefab.
isn't that kinda what I said earlier :p
For sure. I'm just doing a cover song lol
Yes, Item is in separate Prefab, which I assign/equip on character during runtime
Still not what I meant, but let's look at the code
You can have a separate script that only deals with scaling just on pickup methods
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.
ok, first off you don't need to scale each child individually
scale is inherited through the hierarchy
also, you don't need to access transform through skinnedmeshrenderer. It exists on GameObject as well
Hi, Im looking into using unity for an emulation front end, but theres a couple things that Im not really able to get a clear answer for.
Is it possible to:
- Open a new window like you can with javafx or similar and send data to and from?
- Display items in a grid or list based on info pulled from a database (Title, image location, that sort of thing)
- Create drag and drop behavior and/or a file selection window for files and read those files in runtime?
@thorn ravine this isn't enough information. Idk where _addedPartsInstances is being set. Could be an empty array in which case no scaling would happen.
should just scale the root item object anyway
It is in the ReassignMesh method. It is in the Pstebin
That's the thing that it doesn't work that way
All addedPartsInstances are Initialiazed into avatar object
ah ok, yeah I see where you're adding them
That's how it looks like in the hierarchy in Play mode
So item equipping script works fine, it just the scaling doesn't work
really, this should all be as simple as:
Transform anchor;
float scale;
public void OnPickedUp(Transform itemTransform){
itemTransform.localScale = Vector3.one * scale;
itemTransform.SetParent(anchor);
itemTransform.SetLocalPositionAndRotation(Vector3.zero,Quaternion.identity);
}
Why is the max x value 1.23 and min value -0.16 at the edge of the screen where my mouse cursor is
Is it due to my screen size?
I thought Max would be 1 and min 0 no matter the screen size
I could be wrong but maybe try using .Magnitude
This small tech demo was put together in a few days, as I wanted to see how well I could replicate the physics of Sega Rally Championship 1995 in Unity. It's definitely not a 1:1 remake, my version is a bit slower and heavier, but the base idea is there.
As of now, this game is just a tech demo, and won't be worked on further for now. This will...
does anyone know how they pulled off this camera effect?
im not sure what they are actually doing
I would assume cinemachine with a spline
maybe, it doesnt seem to be running along a path
I personally don't have the experience of doing that however I know it's something that it can do
also seems to keep a consistent distance from the centre
It looks like it'd just be a circular spine around the car to me tbh. Splines can do some wild stuff
ohhh! misunderstood
well i mean, like how does it know when to rotate where? thats where im lost
You do mean the intro at the start of the race right?
Just making sure I'm on the same page as ya
nah just like in general
he has a "slide" mechanic present in sega rally
and like,
it rotates the whole vehicle
but like, it doesn't rotate the camera
until the turning has adjusted properly
watch the gameplay, itll show
OH
In cinemachine you can have your camera follow and object, you want it to follow a child object and not the parent then change the transforms of the parent when you want the camera to rotate
I had to figure this out for myself in my project I'm working on
So when he's doing the drifting he is only changing the transform on the mesh of the object, not the parent and probably has a separate invisible child object on the parent the camera follows
well its not really drifting but yeh i get what you mean
It's the biggest part of it really, so once you're able to get the mesh rotation separated from the camera rotation you have the freedom to rotate the car however you want with the parent object doing the real turning
It's kinda hard to explain but it's two parts, the drifting does slightly rotate the whole object but the mesh needs to turn wayyyyy more
So like, I think the best example I can come up with with drifting is
Let's say when your turning your car your mesh is also turned but with a "Drift Multiplier" to it so it turns that much more than when the camera turns
It'd be your offset between the rotation of the car and the rotation of the camera
wait so id like maybe lerp between the current camera rotation and the rotation of the car more or less
that actually
makes a lot of sense
So you'd have the rotation of your whole game object (rotate the parent) with your input method, then call a function that rotates the child mesh as well with an offset multiplier
It probably wouldn't be anything close to perfect but it's a good start
okay yeah thats a good solution
just make sure you make a separate game object for the mesh that is a child under the parent.
I can't over state how long it took me to understand this
ill make sure, ive had that happen before
@cosmic rain
👌 Gl on your project
error, can you help me? as you can see when I hold alpha key then cursor locked and input is false, however in game it has no effect. Mouse is still in the middle of the screen(it is its behaviour if cursor locked and iput is true)
Put a debug in the if and else blocks.
Also one other thing I thought of, multiply the whole car thing by a magnitude of the car's velocity so when your car doesn't look like it's drifting at low speed
Oh dw, I'm not do8ng drifting
Ah gotcha
Thank you btw!!
So the issue is that the cursor is visible?
Try clicking when it's supposed to be hidden.
In the editor the cursor acts a little different so you can still use it
no, that cursor cannot click button
Wat...
it is wierd right
I'm confused I'll let you guys figure it out, I don't wanna cause too many cooks
here
No it's not. I thought you had a more serious problem...
What part is supposed to lock the cursor? Do you understand?
it works, you can click on button when you disable those variables
What line in your code is responsible for locking/unlocking the cursor?
Honestly, this should be in #💻┃code-beginner
wait
those two booleans
{
_input.cursorLocked = false;
_input.cursorInputForLook = false;
Cursor.visible = true;
}
else
{
_input.cursorLocked = true;
_input.cursorInputForLook = true;
Cursor.visible = true;
}```
Wrong.
_input is btw where those booleans are
Why would setting some random bools affect the cursor?
What is the unity API for un/locking the cursor?
You know Cursor.visible is true for both of those?
Yeah I was gonna say
yes, so I can see where it is bruh
Right
So the issue is that the mouse is not properly locked?
Pretty sure this is how it works in the editor. You should test it in an actual build
{
public class StarterAssetsInputs : MonoBehaviour
{
[Header("Character Input Values")]
public Vector2 move;
public Vector2 look;
public bool jump;
public bool sprint;
[Header("Movement Settings")]
public bool analogMovement;
[Header("Mouse Cursor Settings")]
public bool cursorLocked;
public bool cursorInputForLook;
#if ENABLE_INPUT_SYSTEM && STARTER_ASSETS_PACKAGES_CHECKED
public void OnMove(InputValue value)
{
MoveInput(value.Get<Vector2>());
}
public void OnLook(InputValue value)
{
if(cursorInputForLook)
{
LookInput(value.Get<Vector2>());
}
}
#endif
public void LookInput(Vector2 newLookDirection)
{
look = newLookDirection;
}
private void OnApplicationFocus(bool hasFocus)
{
SetCursorState(cursorLocked);
}
private void SetCursorState(bool newState)
{
Cursor.lockState = newState ? CursorLockMode.Locked : CursorLockMode.None;
}
}
}```
this is where those 2 booleans are
What makes you think they affect anything?
I'll ask again, what is the unity api for unlocking the cursor?
api?
API. Methods and properties that unity provides for you to use.
in that script?
In general
SetCursorState()
That's "in this script", not "in general"
that's your function
The api is Cursor.lockState and it looks like he is probably just never actually calling that function from the code he's sent
He's just setting a bool
wait that the issue
I hoped for them to get there on their own though
Yep..
I'd highly recommend reading some resources about C# so you can get a better understanding of how the language works instead of copy and pasting some code.
Unity Learn is a wonderful place for it: https://learn.unity.com/
No he never called the function that he has to set the lockstate
There is code there, it was just never being ran
How can I have a script as a variable? It needs to be able to have any script as value not just one class
Wait can I just use cs MonoBehavior myScript?
Ah I see
You should just be able to create a variable by typing the name of the script.
Or are you trying to have one that global one that can referenced in the whole scene
I want to specify what script from the inspector
Oh just make it a public variable
It will show up in the inspector then once it's compiled
What are you trying to accomplish here? Sounds like an XY problem right now.
I think I might have explained it badly. It needs to be able to hold any script (not just a type of PlayerController fx.)
What will you do with the information of which script is assigned?
All your scripts derive from MonoBehaviour, so that works
It's not the same
You can go one lower and check for Component, or even Object
I could write cs PlayerController controller But I need something like this:
AnyScript script``` I need to store a list of monobehavior scripts to add to another object when the scene loads
Im learning unity 3 years
As a hobby
Im still student
So school is priority
Why don't you just do cs public GameObject example; which would be a prefab containing all the scripts you want. Then just instantiate that prefab.
instantiate it as a child of the other object
Thanks for the suggestion. I'm afraid it won't work in my case though. I have scripts that add different behavior to the object. The player chooses what scripts should be put on the object
Thanks you so much!!!!
The simplest approach here would probably be an enum then
But why?
What is the point
Does it matter?
It feels really overly complicated so we're trying to figure out if there is a better solution
You know context goes a long way
Right now allowing the user to input any script is very confusing
What do you mean? I have one object. It can have 50 different behaviours depending on what script is attached to it. I need a way for the player to choose
public enum MyEnum {
A, B, C
}
Dictionary<MyEnum, Type> dict = new() {
{ A, typeof(AClass) },
{ B, typeof(BClass) },
... etc.
}
public MyEnum[] componentsToAdd;
void AddStuff() {
foreach (MyEnum e in componentsToAdd) {
someObject.AddComponent(dict[e]);
}
}```
@rustic ember
something like this
Your best bet would to have a manager script and have all the children scripts active or deactivated from the parent
So how are these behaviour defined? Do you have interfaces for them? Abstraction?
Truth to be told, I've never used dictionaries before so I'll definitely have a look at how they work. Thank you, I really appreciate it 🙏 🙏
What you refer to as "script" is either a text file containing your code or a C# type. Neither of which can be serialized and then used easily the way you expect.
people are trying to get to the root of your problem because it's possible to yield a better implementation than the road you're currently going down.
No clue what you mean. I have one called HealthSystem, one called Movement, etc.
I'd just use an interface like IRunBehaviour
I don't think you're going to have a good experience creating such a decoupled system if you have no idea what an interface is 🙃
In simple terms this just lets you quickly get the correspondoing type for an enum with dict[e]. THink of a Dictionary as an array that uses any type you want as the "index" instead of an int
Probably true. But there is no way to get good at something without first learning it. No one knows everything from the start, right?
True, but we'd love to give a better solution if there was more context to work with
Awesome!
The solution provided by PraetorBlue was just what I was looking for
What I'd do is use an SO to define the behaviors(some people might be mad about it) and reference them in a list on your object.
Actually that is not a bad idea. I kind of like being able to turn on and off each script during runtime tho
Well, you'll just need to implement that part in your code.
Add/Remove item from list is analogous to enable/disable monobehavior in the scene
I guess you're right. I hoped that there was a super simple solution I didn't know about
Yeah apparently for some people it's blasphemy to have any logic in your SO 😅
I think its valid
The way you imagined it at first is kind of metaprogramming. It's not a simple concept.
Isn't the whole reason of a SO to have preset data and logic in it? Why would it be wrong?
I assume it's not as organised?
Some people believe it should only and ever be immutable data.
i try not to do this with SO's purely because my web dev background makes me feel super dirty to mix data with logic. I end up usually making a plain C# class that can take the SO and do whatever it needs to to it
I would argue that you should use it for that, and then put any actual logic in a Monobehaviour. That way all actual logic remains in Monobehaviours
Then again, who cares
isn't SO just a fancy POCO, I just treat it kinda like a regular class already
My SO-based AI graph begs to differ (you can instantiate SO's just like monobehaviours)
@thin aurora
Never said it not to work 😛
What do I do here?
I think the best way to think of SOs is this:
MonoBehaviour is how we create our own custom component types,
ScriptableObject is how we create our own custom asset types.
There are lots of asset types with logic, like AudioClip, Material, etc...
Yep. Thanks again
could be, whatever you want. i prefer to keep my SOs as models for immutable data and have separate entities that are exposed to the rest of the app. for instance, i'm currently working on a deckbuilder whereby the SOs are the card as they would be stored using a regular old db. the separate entity can then be manipulated into whatever the user does during the run (i.e upgrades). feels a lot cleaner that way. again that works for this project, but im not terribly opposed to logic creeping into SOs as and when it feels appropriate
again though, whatever way works for whatever
And as with all c# related things: there are dozens of ways to tackle a problem, and it really does not matter what you do. Just stick to it. This includes ScriptableObjects, however you use them.
All of these use cases make sense 👍 I just don't like the "youre using SO wrong" that I occasionally see
hey, a question here about good practice for code order of execution.
I'm creating a script that executes an attack. When the hitbox gameobject connects with an enemy, it sends that information back to the player. The player then activates its own hitstop function to make the attack connect look dynamic, with slowdown etc.
Currently attack executes through a switch function that checks the current attack state: windup, active frames, recovery.
Is it okay to just have that hitstop/attackconnect function take place in the same switch function as the above? Or should I create a separate "attack connect" function that executes?
Reason is that it's simpler and more readable to keep all the attack logic in the same switch function. But I'm worried that because it's receiving data from a different script (the hitbox gameobject) there might be a delay in execution between the main script and the hitbox object.
Just going to bump this once since no one responded and there are some more people around now in case anyone has any advice. I know it is a very specific question and I'm probably just going to have to experiment more, but I thought it's worth a shot lol.
What’s a skip list? If you’re just looking for a data structure that’s the most optimal for a* then it’s a min-heap. more info: https://youtu.be/3Dw5d7PlcTM?list=PLFt_AvWsXl0cq5Umv3pMC9SPnKjfp9eGW
Hey, I have an issue. My particle collision system only uses callbacks when it collides with itself. The particles collide with objects in the world just fine, but it doesn't send any messages to my script except for when it collides with itself. Here's my collision setup:
When I set it to not collide with itself, no collision messages get sent.
I think that is what my Priority Queue implementation uses (this is what it looks like: https://paste.ofcode.org/sJp3qM3KKHv7igk3cPShkr) but I'll take a look, maybe mine is just a bad implementation. A Skip List is a neat data structure that does weird probabilistic stuff I'm not 100% sure I understand (wikipedia page: https://en.wikipedia.org/wiki/Skip_list my current implementation of it: https://paste.ofcode.org/mTvbZHAikkVbKDiGrN4Xyf). In my testing my pathfinding is about three times as fast using this implementation of a skip list vs. this implementation of a Priority Queue. I'm hoping maybe there is an even better data structure I could use that is perhaps as much faster than the Skip List as it the Priority Queue.
In computer science, a skip list (or skiplist) is a probabilistic data structure that allows
O
(
log
n
)
{\displaystyle {\mathcal {O}}(\log n)}
average complexity for search as well as
...
i’ve got to go for now, i’ll take a look at it later
Hey Guys, I've got an issue which has me lost (Pretty sure i'm actually just being blind). I'm raycasting from mouse through camera to hit a Texture3D which i'm then stepping at the hit direction through until it hits a specific value, the latter works perfectly however the raycast direction is completely wrong when the object is not in (0,0,0), It's rotation and camera position dont matter and seem to work flawlessly, heres the important code for it and a little gif too! Like I said i'm pretty sure i'm being a bit of a muppet and missing something!
https://pastebin.com/Y79UeHu6
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.
It can't be that, it's happening when I press the jump button, and is happening on the second frame of the jump animation
it's absolutely that
it's abundantly clear from your video
You have an error happening when you press the jump button
So how could I fix it?
a receiver is a script or object that will execute the animation event
basically it's just saying you have an animation event set up, but no script or function to run the event
you either need to:
- delete the animation event if you don't need it
- create a receiver script and/or method for it
I'm using visual scripting
irrelevant
you still need receivers for your animation events
Did you create the animation event on purpose?
This is the jump animation:
That's the code
and it's not relevant
^^
Do you know what an animation event is? If not, read this^
You probably created an animation event by accident if you aren't sure what they are
I know them, but why I need one? It was working fine until yesterday
in which case you can safely just delete it
You tell me, why did you create an animation event if you don't need it?
Let me se if there is one
there is one
Well, weird, there was an empty one
YEp you probably created it by accident
is there someone who have implemented self play using mlagent toolkit of unity?
#🤖┃ai-navigation would be the best place to ask
Thanks
There's another thing, now when the attack animation ends, the jump animation is being set because the grounded variable is being activated, but I don't know why
this looks nice
Sort of a general question rather than a specific one, but, is VR game development really that much harder than normal game dev? Like if you're competent making flatscreen games, would starting a VR project be VERY difficult, or would it not be that much harder?
what are you trying to do?
Hi, I created a script that uses a NavMeshSurface. It's exposed in the inspector. After updating unity, it seems like I can't reference anymore a NavMeshSurface component to the NavMeshSurface public object in the script! Any clue why?
VR isn't any harder afaik, other than just dealing with the XR APIs and having to make your canvases in world space, and having tighter framerate requirements
That's my script
I can't reference anymore a NavMeshSurface component to the NavMeshSurface public object in the script
Wdym by this?
That's the navmeshsurface (above) and below there's the empty reference to a NavMeshSurface script
I can't drag-n-drop the NavMeshSurface into that
and I have absolutely no clue why
I've actually just managed to fix it, I getting my maths bacwards. Basically im recreating RaycastHit.textureCoord but for a texture 3D instead of 2D
it's like they are two different scripts
Did you get the navmesh related errors to go away?
I think you have two navmesh packages conflicting
Aight that's a relief lol
Should be able to. To be clear you're doing this with your mouse, yes?
assuming you have no compile errors etc
y-yeah ahahaha
as everything
it's not a new project, it's been months since I'm working into this, and unless I'm being as stupid as I know I am that's not a beginner problem
the things you think are decoupled are actually strongly coupled. everything should take place in the same function.
there might be a delay in execution between the main script and the hitbox object.
this is a nuanced concern, because there are only very specific circumstances where moving something in frametcan possibly result in a collision / trigger callback executing in framet. the callback almost always gets called in framet+1. this is the origin of many people using raycasts to do physics in the same frame, although if they mastered playerloops they wouldn't have to do that
I also get that, and it doesn't give a NullReferenceException when it gets there, so I don't get how that's not working
okay, usually you use an SDF for this
do you have OnValidate code?
What happens when you drag and drop do you get a red X? Or it drops but then still says None
i assume that's what you mean by a texture3d
https://docs.unity3d.com/ScriptReference/Texture3D.html with a raymarching shader to display them in camera, I did look at SDF approach too however I couldn't find much material on a way to possibly do it
that's what happens
this is a hint
basically it seems like you have more than one definition of NavMeshSurface in your project somehow
Do you have a NavMesh package in your assets folder or something
Also check your package manager - make sure all packages are up to date etc, then delete your library folder and let it get regenerated.
In the same gameobject?
yes
in the assets
I uninstalled it fromt he package manager and manually installed it drag and dropping the directory into my asset folder
that's because it was giving me some errors when I upgraded unity
so... I need to reinstall it via package manager because it is conflicting?
you can look at how clayxels / mudbun does it
I can't find anymore the link and I have no clue why
also the official github page says "drop the files in the assets folder"
don't use the github thing
install it from the package manager
I have a question, does the navmesh works in 2D?
I'll check them out, I think i remember looking at mudbun as it meshes where as we keep everything in camera no meshes generated!
no
use A*path
There's this though
https://github.com/h8man/NavMeshPlus
hmm...
what is your objective? what is this application?
it meshes where as we keep everything in camera no meshes generated!
there is a lot to unpack here which concerns me
Just some messing around in freetime with some very large geological data sets and visualising them, its basically all finished now though!
I saw that it handle 2D, it's good on it?
its basically all finished now though!
hmm...
you're near the beginning or middle of this long journey
yeah, I used that ages ago and it worked well, but it's not super easy
it meshes where as we keep everything in camera no meshes generated!
@sturdy venture for example. the only thing the GPU draws is meshes. so there's no such thing as "in camera no meshes generated." and maybe you meanMesh, but that still doesn't make sense. you can, or cannot have, aMesh, and someMeshes are "free" and some are costly. in the micro sense, i think you might misunderstand a lot about mudbun. in the macro sense, it performs extremely well, and isn't that what you care about?
but what is your objective? the texture3d, what is it?
the video you showed looks like you're clicking at a point cloud of an egg
lol
Thanks
Lol happy to message privately so not to clutter up here, the egg was just a very small sample data as it loads up instantly
VFX graph also accepts a texture3d directly
seems like it worked, thanks
and can render SDFs for you
mudbun has an SDF based picker
in later versions of unity, you can directly render volumes
loads up instantly
hmm
so it sounds like by " its basically all finished now though!" you mean "i am only just getting started"
what is the objective? to render tomographic SAR?
or some part of a photogrammetry pipeline?
anyway if you can express what it is, succinctly, for real, then maybe i can suggest the existing unity features that do this stuff
based on the code you are pretty new to unity and C#
@sturdy venture
we keep everything in camera
this concerns me specifically because it means you might be trying to author a shader
or maybe you wrote some kind of graphics code to render this volume, maybe in plain C# or something
and all this stuff already exists
It's a volume renderer written in HLSL not C# don't worry 😅 The question I posted was me quickly prototyping a feature I had in mind to add, the egg is just an array generated in code to act as random sample data for me to use too vs importing a 15gb+ point cloud file for the system to render
but why write a volume renderer
they already exist, lots of them
what is the idea?
there are at least 2 inside unity
Because none of them did what I needed to do exactly and are limited to Texture3D's 2048 x 2048 x 2048 limit
why do you think it's limited?
they definitely do what you need to do
you don't know 100% what you need to do yet
and there are already tools that do things like picking
the bigger picture question is why do this in unity? what is the goal?
what is this?
Unity has a fair bit of the foundational work required and like I said its just a personal project to extend my own knowledge, I explored existing tools and use some but also wanted to develop some myself to understand the mechanics behind it
then who's we? what 16GB data file is this?
it's not sensitive
in a micro sense, it sounds like you are at the beginning of understanding how to do this. in a macro sense, surely people have tried rendering large volumes, even in real time
the limit you are talking about isn't meaningful is the punchline, at a micro sense
and besides, why wouldn't it be preprocessed?
that's why i am asking what the application is
you will not need to modify this volume data in real time
and if you do, well, you gotta say what the application is
if you look into vdb, you'd see that there's mipmapping as a preprocessing step, and also volume aggregation as a strategy that pre-existing things use
re: everything should take place in the same function. How would you do that when using a separate hitbox gameobject? Currently the hitbox collider is a child gameobject of the primary gameobject which is made active when the entity attacks, and fed data for that specific attack to determine damage etc. OnTriggerEnter is used in the script attached to the hitbox. AFAIK there's no way to use OnTriggerEnter from a different gameobject but I may be wrong.
There's a lot packed into your statement so I'm interested in what a better way would be that would be more strongly decoupled.
I like to have custom shaped hitboxes over raycasts, similar to fighting games where large or small hitboxes are part of the advantages or disadvantages of certain attacks
to extend my own knowledge
anyway, this is the knowledge.
right now it sounds like you are doing something for an architectural firm
or in an academic context
very very hard to say
While doctor finishes his rant, I spotted your issue:
Vector3 rayDirection = transform.InverseTransformPoint(camToVert);
That should be InverseTransformDirection.
would be that would be more strongly decoupled.
you can't do this decoupled
Haha Thankyou, I've actually just rewritten it to remove to remove the needless conversions all together: ``` //Camera to Box ray direction
Vector3 rayDirection = ( hit.point - Camera.main.transform.position).normalized;
Vector3 samplePosition = hit.point;
var depth = tex.data.depth;
var width = tex.data.width;
var height = tex.data.height;
var stp = 1.0f / depth;
//raycasting till the depth
for (var i = 0; i < depth; i++)
{
//making sample position range from 0 to 1
var finalPos = transform.InverseTransformPoint(samplePosition) + offset;
//changing coordinate based on resolution of 3D texture
var scaledCoordinate = new Vector3(finalPos.x * width, finalPos.y * height, finalPos.z * depth);
//Retriving pixel color based on current coordinate
var c = tex.data.GetPixel((int)scaledCoordinate.x, (int)scaledCoordinate.y, (int)scaledCoordinate.z);
//if mouse hits certain valid surface inside volume(expect 0 alpha and certain color provided by user)
if ( c.r > Math.Max(tex.valueRangeMin, tex.cutValueRangeMin) && c.r < Math.Min(tex.valueRangeMax, tex.cutValueRangeMax))
{
var worldHitPosition = samplePosition;
break;
}
//Next step,we movin
samplePosition += rayDirection * stp;
}```
How would you do that when using a separate hitbox gameobject?
there are lots of ways to do this.
AFAIK there's no way to use OnTriggerEnter from a different gameobject but I may be wrong.
sure, not literally that way
it's tough. there is a lot between here and there. you are limited by how expressive you can be in terms of the rules you are trying to do
you also have to look carefully at the unity execution order documentation page
to help you understand what is going on
in terms of timing
Hello, I need help,
I exported my 2D game and there is very bad Quality, How can I fix it?
Text is Too bad
set number under 0 to -1 and above 0 to 1. How to do?
if(num < 0) { num= -1} else{ num = 1}
isn't there a function in mathf for that, I remember there is but I dont remember the name
Could be thinking of Mathf.Sign ?https://docs.unity3d.com/ScriptReference/Mathf.Sign.html
yes
thank you
how can I detect if a button is not pressed using unity new input system?
If its not pressed ?
https://hatebin.com/opkfmmvzqk
how do I define NativeArray like this? can't figure out. Do I really have to just loop through each index?
IIRC you can use the NativeArrayUnsafeUtility to copy a buffer over: https://docs.unity3d.com/ScriptReference/Unity.Collections.LowLevel.Unsafe.NativeArrayUnsafeUtility.html
but I want to check if it is not pressed, not just this frame
What exactly are you building where you need to know if a key is not pressed at all?
doesn't it do same thing as this https://docs.unity3d.com/ScriptReference/Unity.Collections.NativeArray_1-ctor.html#:~:text=public NativeArray<T0>(T[] array%2C Unity.Collections.Allocator allocator)%3B
? anyway I'd like to predefine it, without doing any crap runtime
Yes Im pretty sure you can feed a regular array into the constructor of a native one
I want to make a deceleration system for the player
which, again, isn't same as just hardcoding an array like I showed. I wan't to be able to hardcode it
and for that, I need to check that the player isn't clicking any of the movement buttons(which I read the value from using InputValue)
Hardcode your byte array feed it into a native one
I just wanted to know if there is a way to hardcode NativeArray itself
but it seems like no
So you could check if the value your reading is 0, or there is also .IsPressed which is similar to a continuous GetKey check, though the "new" input system is best used as events rather than used in Update, so it may make more sense to use .started and .cancelled or as Uri suggested, WasPressedThisFrame and WasReleasedThisFrame, since if it was pressed, you know the key is still down, and if it was released, you know it no longer is
Can't you just check isPressed?
Or if you already have cached values, use those
its gives me an error...
What's your code and what's the error
void OnMove(InputValue input){
pressed = input.isPressed;
}
hi,
is it possible to call "add Open Scenes" from a script?
https://docs.unity3d.com/Manual/BuildSettings.html
Not that I know of. Why do you need it ?
And whats the error?
void OnMove(InputValue input)
{
pressed = input.isPressed;
//get the the x axis for the vector2.
movX = input.Get<Vector2>().x;
//turn the movX variable into int and then assign that into the variable facing.
facing = (int) movX;
}
InvalidOperationException: Cannot read value of type 'Single' from composite 'UnityEngine.InputSystem.Composites.Vector2Composite' bound to action 'Player/Move[/Keyboard/a,/Keyboard/d]' (composite is a 'Int32' with value type 'Vector2')
Not sure how that error is related to the code you showed... But you should ask in #🖱️┃input-system Unless if someone here knows
You can't directly use a collection initializer because NativeArray doesn't satisfy the the requirements for a collection initializer.
I added the reset of the code in that function if that helps...
Yeah, you added the line that actually causes the error as far as I can tell:cs movX = input.Get<Vector2>().x;
can you tell why?
because before I added the
pressed = input.isPressed;
``` it all worked
Looks like your axis is not the type you are trying to read it as
.
it did work before
why?
How do you press a joystick
No...
What are you trying to do with isPressed?
What are you trying to detect with that
try to check if the player is not pressing a button and run a function if it is true.
its like a group of buttons
Vector2 vec = input.Get<Vector2>();
pressed= vec.magnitude < 0.1f;``` for example
Is this a 2D composite or just a regular axis
If 2D then this^.
If regular axis then float
Composite according to the error here^ right?
From the screenshot seems it's a 1D axis
That should be a separate action
Show your action configuration for Move
it shouldn't be a 2D vectotr
so what should it be?
The action should be Action Type: Axis
then a 1D axis composite binding
You only use Vector2 and 2D composites for two dimensional inputs
ho didn't know about this, I'm gonna try that
and then the code should just be:
movX = input.Get<float>();
pressed = movX != 0;```
So I have an airship that I am using physics to move (so that I can have a little more of a floaty feeling). What is the best practice for handling the fact that I can't have a mesh collider w/ a rigidbody and Kinematics ?
Should I do it using a second physics scene .. do all the forces over there then translate position movements to the first scene? Or should I go with a compound mesh?
Can somebody give me a medium-advanced Unity topic to research while on a long car ride?
Interesting. I think I know the general ideas of this, but a more in-depth dive might be a good idea
I already have some movement in my 3d game, but I want to make it multiplayer... should I just start with a new Project or is there some "easy" way to make it multiplayer? (I tried making it multiplayer, but it didn't really work properly)
Could also look into Asset Pipeline topics to speed up workflows if you're interested in that kind of stuff. Custom asset importers, asset types, post processing, etc. https://docs.unity3d.com/Manual/AssetWorkflow.html
is there a difference between rigidbody.moveRotation() and transform.Rotate()?
yes
ohhh moveRotation rotates to a rotation and Rotate() rotates the entire object?
well yes
but
that's only oone part of it
MoveRotation cues up for the Rigidbody to be rotated in the physics engine during the next physics simulation step. If it's kinematic it will realistically push objects out of the way.
transform.Rotate() immediately rotates the object directly, without any regard for the physics simulation
Interesting, is there any MoveRotation alternative to characterController or transform?
kind of a dumb questions since it depends on the physics, I can probably just rotate on fixedUpdate
Does anyone have any experience using a neo4j database with unity?
so the [SearchContext] attribute doesn't get inherited. Do I essentially need to make my own attribute if I want it inherited rather than just using Unity's attribute?
If you want to do physics, use Rigidbody
Ask in #💻┃unity-talk
guys what's the current best dependency injection library for Unity? I've heard of Zenject/Extenject but it's no longer maintained so I'm not comfortable to start a new project with it.
whats best depends on your needs, also extenject is not abandoned its just complete/finished. If you want something thats a bit more opinionated than zenject and allows you to do fewer stupid things, try VContainer
I'll take a look at it, thank you
Hey guys im starting to look at Architecture for Unity and trying to make the code clean, i'm searching for Interfaces, Inheritance and Script Composition, and i'm seeing that for example : Damageable(Composition) would be better than the IDamageable(Interface), because of not repeating code with interfaces. So basically want to know if i'm going the right way (?)
Hi, does anyone has the script to a 2D press jump (press longer for a longer jump) like Super Mario
Composition > interfaces/inheritance in Unity.
But your example is not composition
it's inheritance
I recommend making Damageable a completely separate component
My player isnt teleporting button press and doesnt get teleported all the way
share the code
We don't hand out scripts here, but we can guide you to make your own. I described how you can* do it in the other channel
#💻┃code-beginner message
Also dont crosspost
hi ,
does anyone knows how LoadSceneAsync works ?? how does it use the "scene Name" to get the scene and load it ?
It picks a scene registered in build settings with that name
that is what I thought but looks like the scene in build settings doesnt have property name
EditorBuildSettings.scenes is an array of EditorBuildSettingsScene which u can get something called "guid" and "path" from
path is the file path
not sure what GUID is
this is not related to LoadScene though
this is editor stuff
what are you trying to do
im trying to add/modify scenes in EditorBuildSettings.scenes and also load them on the same script.
If you want to load scenes in the editor you should be using https://docs.unity3d.com/ScriptReference/SceneManagement.EditorSceneManager.OpenScene.html
is the scene's file name is exactly the "scene name" ?
thanks but not quite, i need to load scene on monobehaviour script , but add scenes on the editor
what is the scene name ?
example if we have " Assets/Scene2.unity " does that mean the scene name ="Scene2" ?
yes
I could cut that from the path if that is the only way around
Thanks 🙂
hey,
what do i need to include to use "Path"(using ....) ?
https://docs.unity3d.com/ScriptReference/Path.html
This is the standard library System.IO.Path class
that
Thanks 🙂
how did i miss that 😄 , thanks
I mean, it's alright - but the docs you yourself posted are literally 2 sentences long, and contain the answer 😄
it wasnt bold or anything , not my fault 😛
how do game developers make a game use a Newtonian physics system
I'm looking for a script that automatically creates an animation clip that swaps the material of an object's Skinned Mesh Renderer slot to a selected material.
Does anyone know how to do this, I'm new to c# coding, but kinda know how to read the code & have done a bit in python & java
How would I go about creating an infinitely scalable grid like the one desmos has? I'm trying to recreate it but I'm stuck on that part.
Hey, according to unity profiler "Destroy cull results" takes a lot of time in my game, what it is related to? And how to optimilize it?
Why point is (0, 0, 0) but there is a collider (i.e: there was a hit)? 🤔
I'm using Physics.CapsuleCastNonAlloc and it returned an integer greater than 0, so the first hit should have some point.
If I have a script that has "using UnityEngine.Rendering.HighDefinition;"
how do I make it so that this doesnt cause errors if im not in HDRP without commenting it out or anything manually?
Maybe using a preprocessor directive? Not sure if there is one for HDRP
Check if HDRP has a define symbol it adds. If it doesn't, you will have to create an editor script that detects HDRP and adds your own define symbol.
it would need to be like a #define kind of thing yeah...
I just want to be able to include this file in my project, but not have it throw errors if its not in HDRP
0,0,0 is where the hit happened perhaps
lookin at that right now but it needse to stop the entire file from compiling
The collider is very far away from that point and is not so large, so this is unlikely
wrap anything in that file that depends on HDRP in a preprocessor directive. then use the suggestions in that thread i linked to define the symbol if hdrp is present
alright! thanks! I will try that!
Why is unity giving this error Assets\Scripts\Weapon.cs(98,3): error CS0246: The type or namespace name 'IEnumerator' could not be found (are you missing a using directive or an assembly reference?)
use the quick actions in your IDE to import the correct namespace
ok
are you missing a using directive
how do i translate a vector relative to another vector like this? (increasing the distance, but not the angle)
Did you copy this script from somewhere?
It's not a bad thing if you did. I'm just always curious as to how people get these errors. As soon as I start typing "IE", if it's not autofilling, I already know something's wrong.
Ray r = new Ray(A, B - A);
Vector3 result = r.GetPoint(someDistance);```
is the order of points essential?
yes
so the location of these points matter?
i dont know how to explain
like in a 2-1 != 1-2 kind of matter
ok i solved it
thx
no the order of the points in the code matters
the location doesn't matter
Hey,
if I want to attach a reference to a Scene file in a class "scene.unity" how do i do that ?
like for example string type references can be stored by something like this public string txt
GameObject ?
Scene?
you can't really do it
it's been discussed to death
the best ways are all hacks around basically just storing a string
there's no drag and drop scene references
ok but how do build settings does it ?
I don't have access to Unity's source code
is there is a way around through the editor maybe , that is what iam thinking
how do i randomize the location of C to the left/right from B where the location should lay on the perpendicular line of AB?
Vector3 aToB = (B - A).normalized;
Vector3 offsetDir = Quaternion.Euler(0, 0, 90) * aToB;
Vector3 result = B = (offsetDir * Random.Range(-maxDistance, maxDistance));```
something like this
assuming we're looking at the x/y plane in the image
hm i have another problem
i suck at maths lol D:
i get B by getting Camera.main.ScreenToWorldPoint(Input.mousePosition)
but it should always be the same distance from A, because i use a line renderer to connect them, but i dont get it to work
i tried (Camera.main.ScreenToWorldPoint(Input.mousePosition) - A).normalized; but it didnt work
define "didn't work"
show your code
explain what you expect to happen
and show what is happening instead
it gave wrong results, wait
Camera.main.ScreenToWorldPoint(Input.mousePosition) is going to give a point with the wrong z coordinate usually btw
you need to either give it a depth or set the Z of the result
yes i handled that
BlaBla-new Vector3(0, 0, Camera.main.ScreenToWorldPoint(Input.mousePosition).z)
Is there any way that I can shorten this?
_level.time = parameters.levelTime;
else
Debug.LogError("RunParameters.levelTime is null, cannot set parameter");```
it's pretty short already...
I have 8 other variables and counting that I need to set like this, so I'm looking to see if there's a better way already
if not, then 🤷♀️ i'll just go ahead and copy and paste lol
parameters.Set(ref _level, ref .... etc)```
or put them in a collection
and use a loop
great idea, i didnt think of using the ref keyword!
so point A is transform.position
B is Camera.main.Screen....
i want to draw a line from A going to B with a fixed length.
because as of right now, it draws from A to B, which later outputs wrong results when messing with the line
A to B is B - A
also I don't understand what this is supposed to do
What do you do with BlaBla
eliminate z issue
but you're now using a position with x and y as 0?
(Camera.main.ScreenToWorldPoint(Input.mousePosition) + new Vector3(0,0, Camera.main.ScreenToWorldPoint(Input.mousePosition).z * -1)
🤔
oh wait
why not just:
Vector3 point = Camera.main.ScreenToWorldPoint(Input.mousePosition);
point.z = 0;```
faster, clearer, definitely correct.
i just realised this too xD
so what should i do?
Vector3 Cam = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Cam.z = 0;
Vector3 end = (Cam - transform.position);
CreateLine(/*color*/Color.red, /*width*/0.05f, /*start*/transform.position, /*end*/end, /*lifetime*/20);
what does CreateLine do
Vector3 end = (Cam - transform.position); is getting the direction from A to B
not the position of B
If you want start and end that's just transform.position and Cam
yes, thats why i asked what i should do
wdym
CreateLine(/*color*/Color.red, /*width*/0.05f, /*start*/transform.position, /*end*/Cam, /*lifetime*/20);```
Pass in start and end, as your comments imply^
i want to return a point with a fixed distance to a, no matter where ypo click but still on the line between A and the Clicked Coordinates
normalize and multiply with distance
and add A?
For some reason my game screen is not visible and my scale is unknown
saw this on SO:
var distance = dist;
var direction = (hit.point - startPos).normalized;
endPos = startPos + direction * distance;
This suddenly happened
well it does work now, but only if the initial distance is above the wanted distance.
The code I shared you way back when you assked the question will do that
read message above yours
you'd have to show your code
#archived-code-general message this is what I suggest
same issue like i said
works only if the initial distance is above the wanted distance
it should work no matter what
anyone?
Test your C# code online with .NET Fiddle code editor.
It works for any distance
what am I looking at here?
this looks like you're not properly zeroing out the z axis
so it's going into or out of the screen
or your origin point is not at z = 0
A is the red square (start)
B is the end of the line (mouse position)
If i draw the lines, it works fine as long as my mouse position doesnt go below a certain value
show the object positions
ooo
z position seems to be off w8
approved
it works finally
thank you very much
At my wit's end here.... I have a windows il2cpp build that crashes right after the splash screen. The player.log file doesn't show any stack trace. Everything works fine in the editor.
Have you guys ever seen builds crash with no stack trace?
what kind of crash are we talking about
a straight to desktop crash
or a "freeze until it's not responding" crash
I'm trying to understand a conditional function, let me know if I get it right
string test(string txt){
return string.IsNullOrEmpty(txt) ? null : "someResponse";
}
the above statment is equivlant to
if(string.IsNullOrEmpty(txt)) return "someResponse";
else return null;
correct ?
ohh, thanks a lot ❤️
what would be the most efficient way of getting all the game objects with a tag under a certain parent?
so far i just check every object with the tag and then see if its parent is the watned one but i fear down the line this will cuase preformance issues
Why not just create them under the desired parent in the first place
Hey, is anyone else having errors happen when the inspector is in Debug mode? I am using unity 2022.2.0b16 and trying to debug a UI button not being able to be hovered over(aka background image not changing color) after being clicked once, but the inspector is freaking out, and tons of InvalidOperationException: The operation is not possible when moved past all properties (Next returned false) errors.
This person maybe?
#💻┃unity-talk message
you should update unity btw
you're on an old beta version
there's 2022.2.10 (non beta)
Yeah gonna try that first
It has been solid so far so haven't needed to update
At least it definitely seems to be an editor error and not my code, so will do a bug report if this doesn't fix it. Though those take months in my experience to go anywhere 😭
Those this button bug is driving me crazy. If I select out of the player and back in the button works fine again.
hey guys Im trying to make 2D Building system for my game and im trying to make it grid based so things snapso should i use the grid that unity uses like a gameobject with a grid compoenent or should i code the grid fromscratch??
Also how would i get things to snap to the grid?
nvm, misunderstood the question
maybe something like this, but in 2D?
https://youtu.be/VBZFYGWvm4A
Check out the Course: https://bit.ly/3i7lLtH
A simple grid system is easy to setup and customize with the steps in this video. Use it for a strategy game, turn based, in-game editor or more. Download the Unity3D project source as well.
More Info & Project Source: https://unity3d.college/2017/10/08/simple-unity3d-snap-grid-system/
F...
I'm trying to make a script that gives my player some velocity in the opposite direction of the spikes he touches ( so they bounce off the spikes). My spikes are on a tilemap and use tilemap collider + composite collider. When I try to use Collider.GetContact(0).point, Unity doesn't really likes that and for some reason it places the point of connection somewhere in the space. How else can I make a script like this?
This was supposed to be a Debug.DrawLine between the player collider and the spike collider.
You'd have to show your code
{
Vector2 direction = (new Vector2 (transform.position.x, transform.position.y) - collision.Getcontact(0).point);
Debug.DrawLine(transform.position, direction);
rb.velocity = direction * TrapKnockback;
}
```]
Also the spike collider is the overall Tilemap collider
I do. I am trying to get a list of all enemies in a room (they are children of the room they are in)
You're passing a direction vector into draw line
Why?
It needs two positions
Not a position and a direction
I'll fix it
Also the contact has a normal
You don't need to calculate anything with positions
You should use the contact normal
Okay, it shows correctly now
Also it's more efficient to do collision.GetContact(0)
it doesn't have to copy the whole array that way
so should I use collision.contacts[0].normal or collision.GetContact(0)?
collision.GetContact(0) replaces collision.contacts[0]
👍 thanks, it's working now
anyone know how I can align a particle sub emitter normal with the normal of a collided object
If anyone has any suggestions of data structures that could be good for the "Open Set" of an A* pathfinding algorithm I would really appreciate suggestions. I've been trying a lot of things and so far the best thing I have found is my implementation of a Skip List. Also, if anyone knows anything about Skip Lists I would love feedback about my implementation as I didn't know anything about them before today lol.
Here is my current Skip List implementation: https://paste.ofcode.org/wT3X8ykCDeHEFstP3cEyPW
What is better use a audio clip on audiosource component or use AudioSource.PlayClipAtPoint ?
Avoid PlayClipAtPoint when possible because it instantiates a temporary gameobject and destroys it after the clip is over
This is kinda expensive just for playing a sound
!code
📃 Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
What are backquotes
hey everyone, does anyone have an idea on how to check if the player is following us on social media ? (in order to give them an achievement for each social). Do I need the user to login to each social to check that ? is there a easier way of doing so ?
` <- this
'
```
ook
no\
so what do
bc i do 3D sounds
and PlayOneShot need audiosource component
Hm? Use an existing audiosource if possible
So i need to put a audio source on all character
Why not?
You can also make your own audio manager that pools audiosources
Or use some audio middleware like FMOD/WWise but that's different
is it possible to serialize public data as readonly in the inspector only ?
like i wanna be able to modify a string from another script public string txt
but I dont want it to be available for me to modify the value of txt from the editor, just read it , is that possible ?
readonly blocks the other script from modifying the variable ... so it doesnt work in this case.
I need to use 2d pathfinding in my game, is there any way to do it without the asset store or simulating it somewhere else?
creating your own algorithm, although there’s no real point unless you want the practice
I just didn't want to purchase a $30 package for something small
iirc there are several A* packages for free
Also I have more complex shapes than cubes and capsules for navmesh
How would I get those to work?
depends on what package you’re using, tinker around with whatever you find, it’s likely quicker than writing one from scratch
thanks a lot 🙂
i moved on and now im in a bit bigger problem 😄
im trying to add items that i have on a list<> to an array
Maybe consider using Lists instead of arrays if the size of the collection needs to change often.
is it possible to add items on a list to an array ?
as far as i know array can only be defined in the following way
array = [list[0],list[1]....];
but I dont know how many items on the list
unfortunately, it has to be an array, it's a part of an api that i dont have opensource for
int[] iArray = new int[iList.Count];```
Pick a size large enough for all possibilities.
iList.ToArray() will create a new array from a list
but it will have to allocate it
remember i have to modify an api's array , so i could convert my own list however i like but i need to define the api's array to that value
can i just do that ?
iArray = iList.ToArray() ?
I have no idea what the API looks like
if that is all i need to do I love it 😄
just an array of a custom class but we could useint as an example
ToArray would return you a copy of the List. If you're wanting a copy of it, that'd be what ToArray does.
why cant i move the gameobject?
Because you've frozen the object.
im trying to fix it but this means not equal to right?
or is it -=
Sure, but that's not assignment if that's what you're trying to do
ik
Thanks ❤️
Thanks ❤️
is this correct?
If you just want to stop when you aren't pressing anything.. try: cs myRigidbody.velocity = Vector2.up * speed * Input.GetKey(KeyCode.W) ? 1f : 0f;
What you have added is pointless
why doesnt it work?
Because you never unfreeze the object.
oh you need to unfreeze it?
Of course
Look through RigidbodyConstraints2D and apply the obvious one
how do i assign not equal?
You don't. You assign what you intend to assign
i did it
oh my god
idk how to optimize it
and i dont care
also its not working how i wanted to and now im sad
What're you trying to do?
I have a question, I want to modify an Animator State Machine's motion, is there a way to do this? All the information i've found is outdated or the code doesn't work as it was found, there are new APIs it seems but documentation links are dead apparently...
This is the field I'm trying to modify
Like 40% of this code doesn't do anything
any time you set .constraints it sets the value completely.
If you want to combine two things use |
Like .constraints = RigidbodyConstraints2D.FreezePositionX | RigidbodyConstraints2D.FreezeRotation;
this is also completely redundant as it's covered by the fact it's an else to those two conditions
I have a rigidbody that eventually collides with a simple sphere collider. If this hit normal points a certain direction I want this rigidbody to stop moving. This is easy enough. But if the normal is a different value I want to add an impulse to repel it while maintaining its momentum. The problem I have is that once the rigidbody's collider hits the sphere it stops, so in the case of the added impulse all the existing momentum is gone.
use a trigger collider instead and just use the opposite of the rigidbody's velocity instead of the hit normal to do your direction calculations
hey, Im facing an odd problem
I think list get corrupted after deleting an item of it on the editor (inspector)
I have a custom class the holds info of the scene objects , its NAME , COunt in the scene and GUID
once i delete one of the items from the list on the inspector and try to load it again the list get corrupted
i looped through it , the name is correct , the count is correct but the GUID of all item became " 0000000000000000000000000" what is going on ?
I think I ran into a bug this time...
unity 2021.3.5f1
i debuged the list before and after modifying the list guid certainly goes to zero and also some references became NULL! , it wasnt null before
hey,
How to assign List<customClass> without it being a reference to the original List<customClass>?
i wanna try making a temp list and use it for reference instead
List<MyClass> originalList;
List<MyClass> copiedList = new List<MyClass>(originalList);
Heyo, I want to keep adding torque to an object every .1 seconds while a key is held down. Would a coroutine be best for this purpose?
rb.AddTorque(torque * 10f * Time.deltaTime);```
Hi, I'm using the unity starter asset first person controller. I'm trying to add my own input into the starterassetsinput script, but it doesn't work the way I'm intending. I'm trying to have events fire once, but when I press the key, it fires for every frame the key is pressed. How would I change this
I already know about buttons and events
like started
and cancelled
Where would I place the code?
but the thing is the unity first person controller doesn't use that, and I don't want to refactor the code