#๐ปโcode-beginner
1 messages ยท Page 714 of 1
are you rotating the parent gameObject?
which object is the camera attached to
the "Head" game object
Looks like a cinemachine camera nested in the player.
then you would have the anchor as a child of Head
that's the one that's rotating, right?
you would have the anchor rotate with it
Can I see your CinemachineCamera settings?
is there any reason why making the spawn point a child of the camera itself is a bad idea
cuz like it works but it seems like the kind of thing I probably shouldn't be doing
@balmy vortex can I see your movement script and cinemachinecamera inspector settings?
movement script https://paste.mod.gg/owdyfcqfbknc/0
A tool for sharing your source code with the world!
camera
Which camera do you have set as the _camera variable?
the main camera, why?
That's not adviced since the CinemachineCamera gameobject controls the main camera. Think of it adding a brain to the main camera and it manipulates it.
You should rely on moving the Head gameObject since the CinemachineCamera is following it.
I'd also advise grouping the CinemachineCamera with the main camera both nested in a parent gameObject for organisation purposes.
Because the camera is just for capturing the scene in most cases. You would be better to child it to the Head like someone previously said.
void Start()
{
distToGround = GetComponent<Collider>().bounds.extents.y;
move = InputSystem.actions.FindAction("move");
jumpAction = InputSystem.actions.FindAction("jumpAction");
move?.Enable();
jumpAction?.Enable();
}
btw, I changed your null checks and add the ? so it will try to enable it if it isn't null.
Reference for you: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators
though in 99% of cases you shouldn't use ?
Really? I wasn't aware of that.
you shouldn't use them on anything deriving from unity's Object
Ah ok, noted. Cheers.
they can't overload ? so in some cases (usually relating to object destruction) that check is not reliable
using it on an input action is fine but in the above example seems bad because the action will surely need to be used elsewhere
yo anybody got experience with Unet?
it displays black objects that i can phase through
Unity 5 is 10+ years old, any reason why you are using it?
my pc sucks
godot time
i prefer unity tho
i think once you spend abit more time using unity 5 + unet with no support you might change your mind ๐
newer unity versions are probably better anyway as you can remove packages from projects and use more efficient renderers for low end hardware
hey so like how do you delete excess projectiles like this without nuking their prefabs?
Here's my spawner and prefab code for context
spawner --> https://paste.mod.gg/edzuzqzszrit/0
prefab --> https://paste.mod.gg/ffjzxkiutsqb/0
There's no reason to "nuke the prefab" and doing so wouldn't delete the projectile in the game anyway
To destroy objects in Unity you use the Destroy function
This would be a good place to use object pooling however
after x amount of seconds, disable projectile and add back to pool
yes but idk where to put it cuz if I put it on the prefab itself to carry over to the copies the prefab also gets deleted with them
Right now you're just calling Instantiate and ignoring the return value of it.
Instantiate actually returns a reference to the object it creates. You can store that reference, in a list for example, then you can do things with it later.
What do you mean
you destroy the instance not the asset
"put it on the prefab" is vague
oh well how do I do that then?
the prefab script
shown here ^
The script on the prefab itself will not be running code like Start etc
So that would not destroy the prefab
Only instances
E.g. if you called Destroy(gameObject, 5); in Start it would work fine and only destroy the instances
Alternatively, you handle them from the spawner
wdym
well how do I do that?
Show what code you put for that
Wait I see your problem
A tool for sharing your source code with the world!
Why do you have your "prefabs" in the scene?
That's not how prefabs works
You need to drag those from the scene into your asset folder then delete the copy in the scene
Oh wow yea, some critical miss understanding happening right now ๐
Then have your spawner reference the prefab from the asset folder
Then it will work fine
Because you'll actually be using a prefab
the copies have their references removed when spawned like this though
you need to init them post spawn then with these references
but why does it need the player and camera transform?
(using a prefab asset is the correct thing to do)
player body to get the players position to despawn itself after it goes a certain distance away from them
camera to know what direction to move in
the former is probably redundant now but ya
ok well how do I do that?
Get the component and assign to the variables
Make them public to do that.
Or add some function to assign this data
FireballScript? You tell me you made it
If get component confuses you then please read up on it it's very important
i don't think the ? is good here, it will make it fail silently instead of failing fast
I did mention it earlier.
I posted a Unity learn link for it @balmy vortex
Someone corrected me earlier. Not sure what you mean by "fail silently" and "failing fast" or the repercussion of either. Could you please elaborate?
if one of the actions there exists but you mistyped it, ? will mean that you don't get errors, but you will get bugs instead due to the intended action not getting accessed
letting it fail fast and generating an error message instead of trying to continue would let you catch that mistake
Hey! I have some ScriptableObjects that I need to load on Awake. I tried using Resources, but that freezes the game, even with only three ScriptableObjects, so Iโm looking for a better approach.
Why do they need to be loaded specially instead of just assigned to fields?
Because I'll have many of these scriptable objects, and I don't want to manually assign every one of them
Have one scriptableobject hold references to the others ๐
Then you only need to assign one in scene
But you may still run into that freezing, loading data is still loading data
Or make an array and drop all of them there. Takes less than 2 seconds.
Let me try this one, and see if it works for me
I have a
public class ScriptableManifestManifest : ScriptableManifest<ScriptableManifest>
From doing this myself lol
Well it doesn't work because I have an interface that I reference, and all of my scriptable object inherit from this interface.
Wouldn't that make it work better because they share an interface?
Canโt serialize interfaces
Yep
Are you sure resources was causing that freeze?
Yeah, I removed the loading part and it was working fine
Been abit since ive used it but it shouldnโt be causing a notable stall with that light of a load
Stuff like photon still rely on using it nowadays
Wait actually no.... it doesn't cause a freeze now.
so something else is causing the freeze
i will accept my 10 morebillion dollars to my paypal ๐
you can change it to be Addressables instead of Resources, if you're referencing prefabs inside the SOs and they're large then that's possibly what causes it to slow down. Change the prefab reference to be an AssetReference so the prefab isn't loaded when you load the SO and you only load it when you need it. With addressables you can also load locations or the SOs themselves async as well which might help and only load the data you actually need instead of everything right away
I've tried to use Addressables, but the unity doc says that it is unsupported
what's unsupported?
what unity version are you using?
6.1
no way addressables are unsupported on 6.1
the doc itself is just old and prefers you refer to 6.2 docs instead of 6.1
it's saying the unity version is unsupported by unity
nothing to do with addressables
6.1 was removed from the "supported" group when 6.2 came out
ohhh okay.
You can also serialize them as ScriptableObjects and then cast to the interface
I'll try the addressables approach and then come back if it didn't work.
ask in #๐ฆโaddressables if you need help and ill maybe answer ๐
The addressable approach does work, but I have to rename the addressable name to perk by hand.. Isn't there a better way?
I question the assertion that Resources.Load freezes your game btw ๐ค
do you mean there's a hiccup, or a full freeze, or what?
The game doesn't respond for a second, but I figured out that it wasn't caused by resources.
yeah I would say make sure you use the profiler
The what?
The profiler - it's a tool for measuring performance and will let you see what causes any particular slowdown
ohhh. is it like a package or asset?
The cpu exceeded my target frame time...? that's what's causing the freeze, i just don't know how to fix it
It's a built in tool in the editor
yeah i found it
@foggy yoke make sure you enable "Deep Profile" and change it from Timeline to Hierarchy for easier viewing. ๐
Resource: https://support.unity.com/hc/en-us/articles/210223933-How-can-I-profile-a-specific-part-of-my-code
Symptoms:
Not all user code is shown in the Profiler, and Deep Profiling slows down my application.
Cause:
ย
The built-inย Profiler is not profiling all method calls. Also, Deep Profiling caus...
well unity crashed..
How? did it just stop responding or actually closed and loaded an error window?
yeah.
yaayy
Which one? If it stopped responding the entire app would just go white.
it did, and it showed the bug report window
That could indicate a infinite loop or something close to it.
You can add using System.Linq; and use List<ScriptableObjectScriptName> scriptableObjects = new List<ScriptableObjectScriptName>(); or you could [SerializeField] it.
They're easier to work with than arrays, imo.
Do u guys know how to fix this bug? I think it's related to the VFX asset I imported
TransientArtifactProvider::GetArtifactID call is not allowed when transient artifacts are getting updated
This is the best I could find. Hopefully someone else may have a better solution.
I have a rectangle where my arena is, how do I make it so that the camera only captures the inside of the arena regardless of screen size?
Since resizing seems to make it zoom in or out
Definitely an odd bug. I have not done anything, but it's gone
You could create two empty GameObjects called "Left" and "Right" and use Cinemachine and Cinemachine TargetGroupCamera for dynamic zoom.
for a 3d it wouldn't be much different right? Maybe two objects on the corners
You can add more than two targets for the group i.e. 4 and adjust their positions and the weight on the component.
So, you could create 4 gameobjects representing screen origin { 0,0 - 1,0 - 0,1 - 1,1 } or name it whatever makes sense.
does the SO class have to have its own file or something?
It's a package you have to install through package manager. Maybe watch a Youtube vid on Cinemachine. It basically gives the main camera a "brain" so to speak.
Oh, new using for Cinemachine is using Unity.Cinemachine; I believe.
Yes, it must be either the only object declared in the file or the one that shares a name with the cs file itself in order to work in the editor. the same is true of components like the NetworkBehaviour you've defined in that file which is why that works but the other does not
Would you recommend he remove the serializefield and make the scriptableobject field public and move the class to another file of the same name as the class?
Would you recommend he remove the serializefield and make the scriptableobject field public
no
unless they need to access those variables outside of that class it should be private
How would he access them from the public ItemPickup creating a public ItemData variable?
currently they are not accessing them from that object, just an instance of the SO. presumably they will be adding relevant methods or properties to the SO to access or modify its state
i think i made em as such out of habit, this inventory system differs from what ive made before so im just working and seeing how it goes and change stuff when i need, also thanks
Does anybody here has experience working with additive game updates using assetbundles?
I dont want to just resend a link to a message thread of mine that was left unanswered
don't crosspost too. if you need help with addressables then keep the issue in the addressables channel.
And what do I do if it will stay unanswered for a while?
My friend got this mesh from the asset store and it lifts off the ground while the collider is at the ground.
any idea why this happens cuz we cant figure it out?
In fact, don't even breath. ๐
then link to it again in that channel providing a quick overview of what you need help with
do what everyone else does, in meantime do your own debugging / fixing
I dont know what everyone else does for this, thats what I am asking in that thread
not a code question. but the collider and mesh should be separate objects so that you can adjust everything to match the mesh's pivot of being at its feet
They basically just told you to have patience, dude.
using UnityEngine;
public class CameraMovement : MonoBehaviour
{
public float sensX;
public float sensY;
public Transform orientation;
private float xRot;
private float yRot;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update()
{
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;
yRot += mouseX;
xRot -= mouseY;
xRot = Mathf.Clamp(xRot, -90f, 90f);
transform.rotation = Quaternion.Euler(xRot, yRot, 0f);
orientation.rotation = Quaternion.Euler(0f, yRot, 0f);
}
} using UnityEngine;
public class CameraMovement : MonoBehaviour
{
public float sensX;
public float sensY;
public Transform orientation;
private float xRot;
private float yRot;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update()
{
float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;
yRot += mouseX;
xRot -= mouseY;
xRot = Mathf.Clamp(xRot, -90f, 90f);
transform.rotation = Quaternion.Euler(xRot, yRot, 0f);
orientation.rotation = Quaternion.Euler(0f, yRot, 0f);
}
}
Why my maincamera spaw 10 blocks behind player? I have done everything but still not working
!code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
It would be nice if you didn't post your code twice and if you could put it in a codeblock
```cs
<pastecodehere>
```
also unrelated to the question you asked but don't multiply mouse input by deltaTime https://unity.huh.how/mouse-input-and-deltatime
The code only controls the rotation, no?
oh sorry
Are u using Cinemachine?
delete giant wall of text, use links in the bot message to send the code properly
its fine lol just do it properly from now on
was gonna say.. code you sent has nothing to do with spawning a camera 10 behind
hey so like I'm trying to set this --> [SerializeField] public Transform _camera; on my prefab but when the prefab copies itself it doesn't carry over the _camera reference, leading to an error.
is there any way to set it in the spawner itself or like how do I fix this?
spawner code --> https://paste.mod.gg/cvbbkhqkgvlw/0
prefab code --> https://paste.mod.gg/nnukwnndutio/0
GameObject.FindWithTag
var myInstance = Instantiate(etc.. myInstance.SetCamera(myCam)
a few things to note here:
- prefabs cannot reference scene objects, so it's likely referring to a camera prefab which is not in the scene (or just nothing at all)
- you don't need both
publicand theSerializeFieldattribute, public variables are serialized by default - rather than relying on a reference to the camera just put a method on the
FireballScriptthat takes the desired direction and have the spawner pass that in immediately after instantiating it FireballScriptis a bad name, it's obviously a script you don't need to include that in the name
yea no reason to pass an entire camera here, just pass what you need from camera directly
rather than relying on a reference to the camera just put a method on the
FireballScriptthat takes the desired direction and have the spawner pass that in immediately after instantiating it
how do I actually do this though?
Instantiate returns a reference to the object, so store that in a local variable and call the method on that local variable
var myInstance = Instantiate(etc.. myInstance.Init(dir);
@balmy vortex did you watch some YouTube vids on Cinemachine? I think that would help you understand a bit more about what you're trying to achieve.
does anybody have any resources on SendMessage()?
what send message are you talking about, there are multiple
the best resource of them all is this single sentence: "Don't use SendMessage"
Just go to Unity Scripting API
hm? why?
if its Input System its okay..just upgrade later
like how do i use send message myself
because it relies on reflection and simply getting a reference to an object and calling the method you want directly is so much better
are you talking about the Input system one or MonoBehaviour?
i want to do what the input system des in the terms of sending out a message to other coimponents but in my own script
yeah don't do it that way.. its not good
ah....
either get a reference and call the method directly or use an event
for Input System its okay to learn, but you should do references for components
well now that you mentioned it what's wrong with using it with input
pretty much every other way to receive input from the PlayerInput component is better than SendMessage
similar issues but its imo acceptable to learn the basics, its quick way to get Input system going but you should learn Unity Event at least if not actual Action events
why's the playerinput compoentn exist then
to make it easier on you
SendMessage isn't the only option for the PlayerInput component. nobody said anything about not using it, even though not using it is also an option
is 'broadcast messages' better>
You don't have to use it though PlayerInput, you can perfectly just generate a C# script from input map and use those
that's basically the same thing but for multiple objects which probably means it's actually worse
start with Invoke Unity Events it will be the most familiar to you
ok
if you ever used a UnityEvent or similiar like Button OnClick its like that, link a script/method and you get the CallbackContext
if all this is the beginner method how am i supposed to be doing this
I'll go do that then!!! ^_^
just real quick- if i have this code
{
PlayerGrapple.StartGrapple();
}```
how would i translate this to callback
just as example
you see the InputAction section for example fireAction.performed += Fire;
how do I actually pass the direction along to the copy though?
put a method on the FireballScript that takes the desired direction and have the spawner pass that in immediately after instantiating it
yes how do I do that?
you do that by creating a method on the FireballScript that takes the desired direction. then you can have the spawner object pass that direction in by calling said method directly after instantiating it.
So in void update I'd do like, GrappleAction.performed StartGrapple?
you would only subscribe to the event once, not every single frame
did you click on the links I sent lol
I tried
it explains everything in and out
what's (dir) supposed to be here?
that would be you passing the desired direction as an argument to the method. which is the entire fucking point here
the direction you want your prefab to use
so it can do transform.forward = dir
kk
CallbackContext doesn't have isPressed
what does callbackcontext do then?
information callback about the action you triggered
from the docs here is example for a tap shot vs a charged shot
void FirePerformed(InputAction.CallbackContext context)
{
// If SlowTap interaction was performed, perform a charged
// firing. Otherwise, fire normally.
if (context.interaction is SlowTapInteraction)
FireChargedProjectile();
else
FireNormalProjectile();
}```
this is what I was explaining yesterday about how you can switch this from Held shooting to Tap shooting
alr, so it'd be like Context.interaction is Pressed?
idk why you keep mentioning Is Pressed lol its not relevant here
isPressed comes from if you use InputValue
so like if i have my input to trigger with bossed pressed and released how do i check in the code if that interaction was from a press or from a release
like I mentioned before, you have the started and canceled performed states
canceled is usually when you "let go" of the key
so contect.interaction is started?
You realize these are like examples? you have to create these methods and not copy verbatim
you either subscribe a method to specific action state or you check it within the method with CallbackContext
test it out first so you can get an idea of what its doing..
put the Unity event like I showed . You see whats called by default mode button with no Interactions mode set.
public void OnFire(InputAction.CallbackContext context)
{
Debug.Log($"started {context.started} or canceled {context.canceled}");
}```
you will see it gets called 3 times
Started being True, then Started being False and Canceled for let go
or Performed will run when it has done the singlePress instead of the initial press
then do i still need to have all the stuff in on enable and stuff that it shows in the unity docs example or do i just need the functions and the invoke unity events on the player input
the .Enable stuff is if you deicide to instead using the ActionMapClass instead of PlayerInput component
InputAction too iirc but I haven't used that
one last question- how do i get the vector2 of stuff like the mouse and movememnt inputs
the docs didnt talk about that (that i could see)
Input.mousePosition?
you can access the mouse devices OR make an input action that you can use
Oh, sorry, you're using the new input system.
the ideal way is to use an input action if you desire mouse and controller inputs to work
eg
public void OnMove(InputAction.CallbackContext context)
{
Debug.Log($"v2 {context.ReadValue<Vector2>()}");
}```
if using UnityEvent mode for example
oh it's the same! Okay! I think im ready
if you want to just test or bodge before getting the right actions, you can check controls from Mouse.current
but something like what nav suggested (for example) should be your final solution, as it'll be easier to work with
I can't seem to find a callbackcontext type
make sure you have the using using UnityEngine.InputSystem;
i do
do you have the InputAction.?
its nested in the InputAction
CallbackContext isn't a free class, it's nested inside InputAction
so you need either that or a , i think would be the usage...using static UnityEngine.InputSystem.InputAction.CallbackContext;
yeah that works too
you're one level too deep for the using static there i think
ah yeah just using static UnityEngine.InputSystem.InputAction;
whoops, was thinking of the using static X = Y; thing
if (ctx.interaction is ctx.started)
isn't right- what's the right way? So sorry for all the questions
started is a boolean on the ctx itself
you might be thinking of phase, which is an enum
interaction actually afaik is a Interface for Interaction type
(yeah i misread there at first, whoops)
as per unity example here i posted #๐ปโcode-beginner message
might help if you explain what are you trying to implement this exact moment, instead of guessing it lol
im trying to check if the interaction is astarted or canceled interaction
so i'd do if (ctx.started) ?
I showed you here
#๐ปโcode-beginner message
those aren't interactions
started/performed/cancelled are phases
interactions are hold, tap, slow tap, multitap, release, etc
also How and What button mode / interactions play a difference in phases
then i need to check if the interaction that was performed is a press interaction or a release interaction
canceled is released
{
if (ctx.started)
{
PlayerMovePlayer.StartSlide();
}
else if (ctx.canceled)
{
PlayerMovePlayer.StopSlide();
}
}```
so this?
public void OnFire(CallbackContext context)
{
Debug.Log($"started {context.started} performed {context.performed} canceled {context.canceled}");
}``` put Log in your method you can test it yourself what the phases are doing
and see how Interactions affect that behaviour
Is there a button.OnPointerHover event or is that only a function?
ahh
that goes directly on the element though
how do I make it go directly on the elemtent?
it worked :D tysm!!!
put the script shown in the docs on the actual button
oh yeah that's already apart of the button. Are there any other steps I need to perform or will it auto function?
it should already function if you have EventSystem in the scene
I do
yeah it works, ty.
Quick question though, is it possible to have another script listen for when the OnPointerEnter occurs? Or is that not possible since it's not an event
tbh I don't think so, but what I usually do is create a separate event for what I want, hover, click etc.
public event Action<Button> OnPointerEntered
And unity/c# will know what I'm talking about?
well if you subscribe to specific event from somewhere else it will
like myButtonScript.OnPointerEntered += ButtonWasHovered
or use intermediary objects
don't I need to add an event listener?
๐ FREE C# Beginner Complete Course! https://www.youtube.com/watch?v=pReR6Z9rK-o
๐ด Watch my Complete FREE Game Dev Course! ๐ https://www.youtube.com/watch?v=AmGSEH7QcDg
๐ C# Basics to Advanced Playlist https://www.youtube.com/playlist?list=PLzDRvYVwl53t2GGC4rV_AmH7vSvSqjVmz
๐ Get my Complete Courses! โ
https://unitycodemonkey.com...
you would have that other script listen
that's exactly what myButtonScript.OnPointerEntered += ButtonWasHovered does
+= subs a method as listener
ahh
Hi, what i did wrong? i was testing and my melee doesn't storage the enemies, i mean, it is constantly Hurting it nonstop, instead of just hurting it once until AlreadyHitDemons is cleared
{
Debug.Log("meele's call'd yeah");
Vector3 meleeRange = new Vector3(attackRangeX, attackRangeY, attackRangeZ);
int hitsCount = Physics.OverlapBoxNonAlloc(meleePos.position, meleeRange, hitDemons, Quaternion.identity, demons);
for (int i = 0; i < hitsCount; i++)
{
Debug.Log("int is not zero, i guess");
Debug.Log(hitDemons);
if (hitDemons [i].TryGetComponent<EnemyBase>(out var enemy))
{
Debug.Log("THIS SHOULD WORK");
enemy.TakeDamage(meleeDamage,0,2,2,transform);
// Don't set HasHitValeria = true here if you want to hit all targets
}
}
}```
that's not a lot of context to go off of
I have this issue where when I look around I can see my own player body any ideas why?
where should it be "storing" the enemies?
i don't see any AlreadyHitDemons there
huh, looks like due the noalloc part made me forget abt it, yeah, makes sense
well, i will add it now, thanks
looks like some offset rotation issue
was thinking more so the cameras position but yeah
question somewhat related to what i said before, since messages are bad, can i do what the input actions does with the invokation stuff but with my own script and own behavior? like let's say i have an "interactable" component and i want the interactable to invoke "interacted" with a door component
is there a way to lerp position, rotation, and scale all at the same time in code?
no, computers do one thing at a time
could i do it with coruoutines?
you can do them in sequence within the same frame and it'll all render out at the same time
or is that bad practice
oh alr
thanks
no im saying the operation you're asking about doesn't make sense
but a slightly different operation is a no-brainer
youre being obtuse rn chris
@primal trench this answers your question
this is an important thing to note in terms of mindset
unless it's a math thing where you can compound operations, then no, you can't do anything at the same time
but computers are fast enough that doing them one thing at a time can look like they're at the same time to a human observer
when i do them one after another vscode says "assigning position and rotation sequentially could be optimized"
show ur code
well, see what it suggests then
it's probably referring to using the SetPositionAndRotation method instead of assigning to the properties individually
it's more "optimized" to use that method if you need to set both because it only ends up being a single call into native code instead of two separate calls into native code
https://paste.mod.gg/jmoxufzjxwwn/0
rn when my player ledge jumps they have to be holding D, i also want the option for them to be holding A to jump left which means a negative velocity. is there any efficient way to do this without creating another if statement and coroutine?
A tool for sharing your source code with the world!
have an arg be the direction as a vector?
I havent opened your code but i presume at some point you will apply force
nah im using velocity
either way you can add a vector to the velocity or assign the new vector as velocity
Jump(new Vector2(-1f, 0f))
Jump(new Vector2(1f, 0f))
yay any 2d direction
not sure how id implement that into my own code ngl
okay ill check yours then
but it should be trivial to have some input direction for force
Ah its very funky
tbf the only thing u really need to concern urself with is the ledgey function and booster coroutine
It may be easy to do as you can invert some force by doing * -1
when A is pressed or?
Perhaps you should instead read horizontal input instead of the D key, if its length is not 0 you can perform the jump (if its direction is away from the wall)
This input dir can also be used to produce the move velocity?
Is it possible to know if the ledge is on the left or right currently?
nah cuz u can ledge jump if either ray is touching it if thats wym
Basically the logic to jump off needs to be changed to be usable for both conditions and therefore should not be hard coded for one of the two.
Lets go back, is this currently set up to only let you jump right?
else if (Input.GetKeyDown(KeyCode.Space) && LedgeTime > 0 && Input.GetKey(KeyCode.D))
yeah thats how i can ledge jump
i could create another if statement for when A is pressed but there has to be an easier way is what i was thinking
also im not familiar with horizontal input reading
is that the input.getaxisraw stuff
Then look at Input.GetAxis() first
We can use this to detect horizontal input AND know the direction of it (-1 x or 1 x)
seems pretty simple
And ideally this direction is also used to perform the ledge jump but you will need to verify that this jump is possible so they dont jump into the wall
Perhaps you should just configure on the ledge if its a left or right ledge
wdym
e.g. have a new script called "Ledge" and have an enum on it to specify which side the ledge is on
Or we figure it out another way based on how its placed or some other data
i mean that type of object is always gonna have 2 ledges
Then how do you think we can tell which direction the player can jump from a ledge?
Hello i am trying to make a dynamic inventory. Everything works perfectly but i have 1 issue ๐ฅฒ when i take an item in a slot i cant replace it in the exact same slot, I have to place it in an other slot and then place it again in the previous slot. but the weird thing is that i am using a function remove() called everytime i do this and i press Escape. it work perfectly for escape but not for the other thing. I've been looking for 3 days but i found nothing ๐ข (parts i used for this feature are between "***")
invManager : get inventory slot and know if an item is already inside (he's the link between all slots)
slotScript : it is the script inside every slot
DragScript : it is the script who add drag & drop to every item
sorry it is a lot of code ๐
There are a few ways to go about it but its useful information we need for a ledge to then ensure a ledge jump is done in the correct way.
A script for the ledge with this data may be easiest (e.g. public Vector2 jumpDir;)
What would I do with jumpdir
we can use it to confirm if the input direction is correct AND can be used as the dir to push the character
e.g. AddForce(jumpDir * multiplier)
Hey I have to use a timer for my enemy behaviour, i have seen that C# itlsef has an TIMER class, can i use that or will that cause problems with my unity project
dont use that
pretty sure System.Timers.Timer invokes its events on a separate thread so you wouldn't really want to use it for unity stuff
aight thanks!
use time.time and math in an update loop tbh
yes that's how i have done it so far, it works but i notice how repetitive it is. espacially if you have to do it multiple times in one script
thinking about creating an helper class which I could use more often
I have a little base class that basicially wraps up a coroutine
Depends on your needs and how you've implemented it.
I think it wont be the last timer im gonna use for an unity project, should be worth it
yee was thinking about something like that
that would work with a static class/method right?
i dont use statics for any of this no
ahhh yeah fair because I would like to have an reference to the timer i just started
A coroutine or async function is the way to go
I have a ray pointing forward from the camera, and I want to be able to detect the type of object I'm looking at (eg, weapon, food, etc). How can I get information of the object using the Ray?
I'd want to get the layer or tag
Raycast with layermask for initial collision, then use TryGetComponent on the RaycastHit result object to see what it might be
if (Raycast)
if (hit.TryGetComponent(out Weapon weapon)
eg pseudocode
or if your objects dont have individual components you could go by the tag of the gameobject:
if( hit.transform.gameobject.tag == "food")
{
dostuff
}
This is true but ideally itโs worth skipping over tags entirely tbh
(Note ideally)
- tags are trash
- you should not use
==, CompareTag is better
yea CompareTag didn't know the syntax out of my mind thanks, and I believe for protyping it gets the job done
No shade here but once you get in the habit of it it doesnโt cost any additional time youโd save in prototyping. The idea here is that tags are hardcoded and a kinda arbitrary middleman. The conponent check doubles as a tag check if you treat components like tags
Many documents and tutorials use tags which is why people get that habit but it really just doesnโt bring anything to the table
i mean it works lol ๐
I never use tags and the only reason id think to use them is to perhaps speed up component retrievals
At that point iโd even prefer the unholy strat of using physics materials as object references for identification ๐
Does anyone know why I can't see a Ray being projected? I know my ray is working because I have a "Debug.Log()" that says whenever an object is hit by the ray, but I can't actually see the ray in the scene view
ok lets get the plumb things out of the way first
is that one enabled?
Nevermind, I forgot I turned off gizmos 
That may only work in OnDrawGizmos functions. You can use the package Vertx to draw gizmos from update
https://github.com/vertxxyz/Vertx.Debugging
Hi I'm trying to make a simple 3d platformer Obstical course project. I'm trying to make a jump button but every time I press the jump button my player continues to go up into the abyss. Is there a condition I'm missing?
if (canJump)
{
if (Input.GetButtonDown("Jump"))
{
jumpForce = new Vector2(physics.linearVelocity.x,jumpSpeed);
physics.AddForce(jumpForce,ForceMode.Impulse);
canJump = false;
isJumping = true;
}
}
else
{
jumpForce = new Vector2(physics.linearVelocity.x, physics.linearVelocity.y);
}
0.5% chance my code runs without errors. 99.5% chance I start debugging before I finish typing.
It's very weird that you're using your current x velocity in the jump force (but that should only lead to horizontal weirdness in and of itself. That else statement seems completely pointless too.
Aside from that, you should show your rigidbody's inspector. Your object is just behaving as if you disabled gravity on it (or in the world)
It only seems to come back down when I move it around in the air but if I leave it then it continues to go up
srry wrong chat heh
you should turn your inspector back to normal mode
it's on debug mode
which makes it hard to read
Also you should share the rest of your code
It's almost certainly due to your code
public bool OnGround()
{
Ray groundRay = new Ray(this.transform.position, -transform.up);
isGrounded = Physics.Raycast(groundRay, out RaycastHit hit, groundDetectionRayLength, groundLayerMask);
return isGrounded;
}
// Update is called once per frame
void FixedUpdate()
{
//Set your Input variables you made to the Axis they are going to be used for. This will allow for you to get the exact axis the player will be moving on be sure to type the exact name of the axis
InputHorizontal = Input.GetAxis("Horizontal");
InputVertical = Input.GetAxis("Vertical");
Vector3 move = new Vector3(InputHorizontal * speed, physics.linearVelocity.y, InputVertical * speed);
physics.AddForce(move * speed_Multiplier, ForceMode.Force);
// Speed limit;
while ((physics.linearVelocity.magnitude > speed))
{
physics.linearVelocity = Vector3.ClampMagnitude(physics.linearVelocity, speed);
break;
}
// ground detection
OnGround();
while (isGrounded)
{
canJump = true;
isJumping = false;
break;
}
// Player Jump
if (canJump)
{
if (Input.GetButtonDown("Jump"))
{
jumpForce = new Vector2(physics.linearVelocity.x,jumpSpeed);
physics.AddForce(jumpForce,ForceMode.Impulse);
canJump = false;
isJumping = true;
}
}
else
{
jumpForce = new Vector2(physics.linearVelocity.x, -gravity * Time.deltaTime);
}
}
private void OnDrawGizmos()
{
Gizmos.DrawLine(transform.position, new Vector2(transform.position.x, transform.position.y - groundDetectionRayLength));
}
}
// Speed limit;
while ((physics.linearVelocity.magnitude > speed))
{
physics.linearVelocity = Vector3.ClampMagnitude(physics.linearVelocity, speed);
break;
}```
This should just be an `if` statement, not a `while`. In fact you don't need either. Clamp only does something if that magnitude is higher anyway.
` while (isGrounded)`
this should also be an `if` statement, not a `while`
And finally here's your actual problem:
```cs
Vector3 move = new Vector3(InputHorizontal * speed, physics.linearVelocity.y, InputVertical * speed);
physics.AddForce(move * speed_Multiplier, ForceMode.Force);```
Why are you adding the current y velocity to the force here?
you seem to be confusing "adding forces" with "setting the velocity"
I'm fairly certain everything in your script that is calling AddForce you actually meant to set the velocity, based on the way your code is written
You should also stay clear of while for now, you don't seem to understand how it works and it's just cluttering your code. It's also very easy to end up freezing your game using it when you don't understand it.
Thank you!! It works now!
I just changed this to be Vector3 move = new Vector3(InputHorizontal * speed, 0f, InputVertical * speed);
you probably want to revisit how you're adding the horizontal velocity when jumping too
and think hard about whether you want to be adding forces or setting the velocity
I need to make this action run the Grind method on the instance of the Grinder script that the player is looking at. This is how the grinded action is set up rn, but I don't know how I can use this with a raycast detected object because I would need to do some confusing subscription stuff.
why can't you use it with a raycast detected object?
wouldnt it need to reenable or something if the instance of grinder changes?
also what if the instance is null when the player isnt looking at it
You absolutely need to manage it correctly, yes. Subscribing exactly once, unsubscribing when the player looks away, etc.
But it can be done
it's a little tricky if you're not careful
Yeah, let me correct my question rq.
Here's the pattern basically:
Grinder currentlyLookingAt = null;
void Update() {
Grinder lookingAtThisFrame = null;
// Note if we don't get a raycast hit, or if the thing we hit doesn't have a grinder, lookingAtThisFrame will be null which is expected
if (Raycast(..., out RaycastHit hit, ...)) {
lookingAtThisFrame = hit.gameObject.GetComponent<Grinder>();
}
// If we're looking at a different thing than last frame. Otherwise, we don't need to change anything
if (lookingAtThisFrame != currentlyLookingAt) {
// Unsub the previous grinder, if any
if (currentlyLookingAt != null) grinded -= currentlyLookingAt.Grind;
// reassign the variable
currentlyLookingAt = lookingAtThisFrame;
// Sub to the new one, if it exists
if (currentlyLookingAt != null) grinded += currentlyLookingAt.Grind;
}
}```
@elder osprey
Oh, alright. I never totally understood the subscription stuff, so I thought I needed to do it in OnEnable and OnDisable
Thank you
Are you making rail grinding in a 3D project that sounds awesome??
No, I might in the future tho, my current game is a lethal-like and to add to the quota you grind items in one of the grinders located around the map
OOOOOhh okay still cool stuff
I need to do this twice because this logic is happening in my inventory script, when the player presses e they can either Pickup, Grind, or Interact
I have been working on a 2D rail grind system in unity. I plan to revisit after doing this 3D project I'm more familiar with 2D.
OnEnable & OnDisable tends to be used for listening because usually monobehaviour activity is similar to clocking in and out of a job, if that makes sense
That makes sense
Would this be able to work in the Interact InputAction method?
Like up here in the method?
Since I'm already doing the raycast in there
If these things all use the same raycast distance, layers, etc you could probably unify all of it
unify?
have one piece of code that handles all the cases
this code is only for when you press a button, so not it's not really the same. In this case it's more straightforward - you just check for the component on the object and run the method directly, no?
Otherwise - you fire the event in the input handling code
and you have the raycast stuff in Update
So it really depends if you're using an event or not
unsafe reference in here!!
if (hit.collider.GetComponent<ItemPickup>().item != null) will throw if .collder does not have an ItemPickup component.
you should be doing something like
if ((hit.collider.TryGetComponent(out ItemPickup pickup) && pickup.item != null)
Does using an event for this case just complicate things? I wanted code to happen once in the Grinder script when something happens, and I think events are the easiest choice for that, no?
yes I think so - it's not clear to me why you were using an event there
but - having the raycast code in Update does make sense often because it's typical to show the user some kind of UI and hide that UI when the action is available
I'm using an event because when the player presses e on a grinder, I need code to be ran on the grinder script.
but why does that need an event?
Couldn't you just have:
void Interact(CallbackContext context) {
if (context.performed) {
if (currentlyLookingAt != null) currentlyLookingAt.Grind();
}
}```
(based on the currentlyLookingAt variable in my code above)
If we just keep a reference around to the Grinder we're looking at currently, it's trivial to call the function without an event
I might be mixing up Grind and some other interaction thing here but you get the idea?
Are Grind and Interact two different buttons?
With this method, I wouldnt need multiple sets of logic for the Grind and Interact events
No, they're both e
yeah exactly
then yeah I would just unify that all under a single interface like IInteractable and put it all in one code section
I might have it so interact is its own thing, and the grind logic is handled in the Interact script if the object is a grinder
lol, we said the same thing
My objects are moving at 1 meter increments for no reason did I press a shortcut or do smth else by accident
Nvm, I might be possible Not Smart
happens to the best of us! ๐
Hi ๐ would anyone be willing to review a project I have been working on. I'm trying to create a 2D rail grinding mechanic in unity. It's been a while since I last touched it but I plan on working on it again and updating it.
https://github.com/lsclarke/Unity-2D-Rail-Grind
I'm using data persistence for my saving and loading system. I have enums that I want to be able to add to directly using this data persistence system. How do I save all enumerated values?
On disk it can be stored in it's string form or as it's numerical value (int by default)
So I guess maybe I'm misunderstanding how data persistence works. I
pretty cool , i'm doing that but in 3D with spline.
do you have a specific concern on it?
Can I not directly save and load to the actual code? I know data persistence saves values and stuff. Like the status of a bool, or the value of an int.
{
None = 0,
Ammunition = 1 << 0,
Finesse = 1 << 1,
Heavy = 1 << 2,
}
But if I want to add a new enumerator with the bit shift, can I do that with data persistence? It seems like there must be a way.
By data persistence do you mean write to some file or do you mean something else?
An enums value IS it's numerical value
So I'm not fully in tune with how the code works. I save to a file, yes
Save the int and that's it
most people save it as int
Ok so maybe I'm not explaing myself properly
You aren't no...
I want to, during runtime, be able to add a new enumerator to WeaponProperty.
wdym a new enumerator ? that means something else , like new "Enumeration" ?
enums are just constants
If you changed to using int instead of the enum type then there would be no restriction
A new "entry" to the enum. Maybe my source was bad, but that article called entries under an enum enumerators.
Like the Ammunition in my code.
Yes
Share some code so we can understand what you actually want or need
It's unclear so far
the design of constant is not to change during runtime
{
None = 0,
Ammunition = 1 << 0,
Finesse = 1 << 1,
Heavy = 1 << 2,
Light = 1 << 3,
Loading = 1 << 4,
Range = 1 << 5,
Reach = 1 << 6,
Special = 1 << 7,
Thrown = 1 << 8,
TwoHanded = 1 << 9,
Versatile = 1 << 10,
Improvised = 1 << 11,
Silvered = 1 << 12,
ExampleToBeAdded = 1 << 13
}```
whats the end goal?
explain what you want to do instead of focusing on a specific solution
These yearn for ScriptableObjectโs
So weapons have weapon types, and only certain classes can use certain weapons. A weapon can have multiple weapon types.
I want the user of this program to be able to add additional weapon types to weapons.
hmm yeah maybe SOs could fit that here
I would use SO enums for this. Just have a list of the SO enums that belong to the weapon . . .
Be ideal for when you wanna add extra into to these too
And you instantiate more SOs with custom names or?
But I'd need customizable SOs. I need the player to be able to create new types
Basically, create a SO_WeaponProperty ScriptableObject. Then, create assets in your project folder for all the names (just like you did for your enum) . . .
You can have a list of these SO_WeaponProperty SOs on the weapon if they have multiple types . . .
Cannew assets be created during runtime?
Yes, you can instantiate or create a new instance of an SO, then name it, but why do you need to create a new WeaponType during runtime? There's no way you could do that using enums (your previous method).
yeah you cant update / make a enum during runtime
Then an SO is not the solution for you.
Or at least not the complete solution.
What I do in these situations is make two separate types:
- The runtime type, which can be directly created by players
- The SO type, which can create the runtime type on demand but can be edited in the Unity editor
Then at runtime, you use the runtime type basically.
Do you mean, you want the player to create new types of weapons?
Is there a way to edit the save file, and then add to the enum when the game is reloaded?
no the enums are built on build
Aight.
You just need to save data in a custom type, it wouldn't be an enum
What do you mean by custom type?
A custom class or struct
So I can do this with structs, but not enums?
c# is OOP make a class that does what you want
Players cannot change code. They cannot add a type to your enum.
But what you can give them the ability to do is change data
so for example if you had:
public struct Weapon {
public string Name;
public int Damage;
}```
You can allow the player to create one of these through UI or whatever
and save it to the save file and do whatever you want
but they can't add an enum value:
public enum WeaponType {
Sword,
Katana,
Dagger,
// users can't modify your code so they can't add stuff here
}```
Well, they can change the data of strings and ints. I don't know of a way to add a new int though
you don't need to have them add a new int
Just save the data they give you
this feels like one of those x y problems https://xyproblem.info/
Ultimately the design here is really going to come down to how much customization you want to give the player
it can get very complicated or it could be very simple
On the simple end it's a few bits of data. A name. some damage. Maybe a reference to a sprite or something.
On the complex end you're basically giving them a scripting engine to write custom behavior
I think they also want something along the lines of "tag" system and only certain classes can use weapons with those tags , but want people to add new tags
And there's a million shades in between those things
In that case you can simply have a string tag or List<string> tags
IInteractable?
An example name for such an interface, yes.
what do you mean by interface?
I mean a C# interface
How would I use this in the current context?
you would make all of your scripts that are interactable in this way (looking at them, pressing e) implement the interface, and then you could just have one piece of code that handles all of them (via the interface), instead of a separate piece of code for Grinders, Interactables, and whatever the third things was you said. Items?
It would eliminate your code duplication problem
Yes. This is what Iโve explained. I used enums because you can add flags and then you basically have bools.
And then the classes will also be customizable, ie. the weapon types that their class can use is selected by them
So basically they just select the tags
You can recreate this in software pretty easily. It's essentially just Set operations.
With the presets youโve seen
HashSet<string> allowedWeaponTags;
// Check if you can use the weapon
bool canEquip = allowedWeaponTags.IsSuperSetOf(weapon.tags);```
Iโll look into it.
You could of course also map each set to an integer value and do bitwise comparisons too. But this limits you to 32 tags for int and 64 for long. It is certainly a lot faster though.
That was what I was doing in the enums
right but it's pretty limiting
Which was the problem
especially with custom tags. And you'd need to keep track of the tag mappings to ints as well
Once again, I find myself greatly indebted to you. I think this is the solution.
Is a kinematic rigidbody for character movement a bad idea if I want a map with lots of physics objects that they shouldn't be able to just walk through?
kinematic will ignore everything else but not other way around
unless you code it not to hit anything with proper checks
Kinematic CCs are definitely a valid option. Like every character control option they have their advantages and drawbacks.
The biggest weakness of it is that it will be very difficult to allow your player to be pushed around externally by other objects.
If you don't need that, it can be a solid foundation.
From what I've read kinematic will move physics objects around with essentially infinite torque
So if I've got e.g explosive barrels then the player could just walk into them and push them around
Bet
Rn I'm using a dynamic rigidbody and I'm finding it an enormous PITA
I highly recommend checking this out, it's really good out of the box: https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131?srsltid=AfmBOoqAFt2j_q_-5JkxdEQDYS7bHXrFxduZnjdElPuBsgUJ1oVRQdfO
thats why most controllers are kinematic based
Thanks mate
even CC is somewhat of a kinematic body
Is this accurate tho?
Because it's a behaviour I wouldn't want
Yep they even call it that in the documentation
yes if you use a kinematic controller you would need to manually implement any "pushback" or "knockback" stuff
oftentimes this is highly situational and worth it
having more control is def a positive
"pushback" meaning "rigidbodies stop you from moving them around"?
meaning they push you around
Knockback at least seems pretty easy to implement manually
for example if an explosive barrel explodes and you want the player to fly back
or a giant hammer swings and knocks the player off a platform
Makes sense
these won't happen naturally with a kinematic controller without you coding it
(although that asset has some of this stuff out of the box)
But what I'm specifically asking after is if you can stop a kinematic rigidbody from pushing other rigidbodies around?
at that point you're just disabling collisions entirely
What I've read online is that they're a '1 way street' where they push rigidbodies around but can't be pushed themselves
or if those other bodies are also kinematic
Hmmmmm okay
In that case would a non-rigidbody cc be more what I'm looking for?
Since the behaviour I'm looking for is that I've got rigidbodies in the scene that the character can't push around, except when performing certain actions e.g punching
if the objects are only meant to rect at specific time why not make them kinematic / constraint locked until they are hit "properly"
i often do that so when my char is on a physics object it doesn't wobble
Okay last question: what functional differences are there between a non-rigidbody cc (like Unity's built in cc) and a kinematic rigidbody cc?
Smort
Where do you define a interface?
in each script?
you define it once, typically in its own file
on top of my head / most obvious one, the Character Controller already detects colliders for you while kinematic rb you have to code that in with something like RB.SweepTest or other physics queries
Does anyone know how I could carry a set of gameobjects over in a scene transition? Ie, I have an object that has to be loaded from one scene to another โintactโ
DDOL?
Bet
Thanks for the help gang
You have 3 options:
- Make them DDOL
- Use additive scene loading. I.e. they live in scene A and you additively load scene B (and maybe unload scene C, leaving A intact)
- Let them get destroyed and recreate them from some saved data
For some reason adding the IInteractable interface to the Grinder script gives this error
Thatโs your hotreloading pluginโs problem
..Which I donโt think is actually discussable on this server, based on how those are made ๐ค
btw there is also this? but never used it myself.. I guess this is mainly for using additive workflow
SceneManager.MoveGameObjectsToScene
SceneManager.MoveGameObjectToScene
oh
yeah this would only work in the additive workflow. You need two scenes loaded at once for this.
Is there a way I can selectively add DDOL to gameobjects that I select while in the first scene (Iโm making a fire emblem-style TRPG)? Not the end of the world if I canโt, just feel like itโs cleaner
of coruse
you can do whawtever you like in your code
It won't become DDOL until you call the function on it
So you can just only do that for the ones the player selected.
Okay that makes sense, but is there a way to then remove it from the ddol list as well?
sure - move it to any other scene with the functions nav mentioned above.
or destroy them manually
Also might be worth elaborating on the usecase here if you want more specific advice.
Eg. For turn based/โroundโ games in general, when dealing with units you might not want to reuse the same objects in and out of rounds and instead recreate them at the start of the round using saved data stored elsewhere
Almost exactly what I typed out and deleted earlier^
what are interfaces useful for? I havent come across something yet where i would use it over an abstract class
Interfaces donโt need to actually do anything, itโs just a promise that it can do something. This allows two very different things to implement an interface that is exclusively what they have in common
you cant use multiple abstract classes cause of inheretence limitation, but interfaces you can implement as many as you wish
well for one classes can implement multiple interfaces, but derive from only one base class. For two - interfaces can be implemented by structs, which can't derive from anything - including abstract classes - at all.
Thanks, maybe this advice can help with my movement system
Psycho example but if I myself am an elevator, I donโt need to know what is inside me, I just need to know how much it weighs. Because of that the only thing I need to know could be defined as
interface IWeightable
public int GetWeight();
then anything wanting to be on the elevator (a box, a person etc) just has to implement that interface and single piece of information without being directly related to eachother like
Human : MonoBehaviour, IWeightable
Box : MonoBehaviour, IWeightable
^ the key point is here is that the elevator code doesn't have to know or care about boxes or humans, it can just deal with IWeightable and so you can write simple code for it that just takes each object's weight
So if im understanding this correctly i could make like an IConsumeStamina and put it on a movement state to make it consume whatever it returns?
then you can use this alongside abstracts, where you might want something like
abstract class EntityBehaviour : MonoBehaviour, IWeightable
abstract int GetWeight();
class Human : EntityBehaviour
override int GetWeight() {}
class Animal : EntityBehaviour
override int GetWeight() {}
Interfaces : functions needs to be implemented explicitly in the implementing class, abstract classes : not obligatory
Okay i think i understand. Thank you everybody!
Memory rule I used when doing my courses, implements you could think of something that every one has to do, every one with legs are able to walk. Abstract somethins it can do but dont have to be able to do, there fore youre are not required to explicitly override it in the extending class
Oh i think i see why this could be useful. Maybe for my situation i could make all objects of an interface decrease their stamina consumption by like 20% or something and they will return differently
for like an upgrade
and that would be required due to it having the interface so i dont need to worry about it being null or anything
the wording here isn't really accurate. abstract methods dont provide an implementation and have to be overridden too
something being null doesn't change here. though yes you could do all of what you described using an interface
Its only required to contain the functions or properties that are not virtual right
thats right my bad, but all abstract methods dont have to be overriden but interface methods have to if I dont remeber incorectly
an interface just specifies what methods have to be implemented
Your confusing abstract and virtual
virtual can be overridden
abstract must be overriden
Think it might be that im mixing it up with Java ๐
im not really sure what you mean here tbh
Time to take C# course hahaha
i did specifically say "and have to be overridden" in the message u replied to btw. u eventually have to implement it otherwise you arent using the class
Iโm sorry let me reword this, I meant that functions or properties are not forced to be overridden if they are virtual?
and yea you are definitely thinking of java when you said implements that isnt a c# thing either
I think I assumed the object orientation worked more of less the same, beg u pardon ๐
yes a virtual method provides an implementation, so u dont need to override it
I'm not very familiar with Unity 3D projects but I worked all day on this project which is just a 3D platformer prototype I have been working on.
this isn't a channel to showcase your work, this is for questions. #1180170818983051344 or #๐โdaily-win
I have a small quesiton, in tutorials when someone is typing into Visual Studio it gives auto complete suggestions but when I try it only suggests things i've already typed. How do I fix this?
configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข
Visual Studio (Installed via Unity Hub)
โข
Visual Studio (Installed manually)
โข
VS Code
โข
JetBrains Rider
โข :question: Other/None
(note that visual studio and vscode are different things)
Thank you so much (I thought i already did this but i guess not lol) ๐
Would transform.LookAt() be appropriate to make my 3d game object face the camera?
or is there something better specific to navmesh agents?
List<Action>
but I want a list of types
not a list of action objects
(Action is a class I've made here, not system.Action)
why do you want a list of types
Maybe it's a dictionary of types that I want? I want a dictionary that maps a type to an instance of that type
This sounds like an XY problem
got it
Dictionary.TryGetValue() exists btw
idk if there's a way to one line it using try get value?
kinda but stop caring about such silly things
why do the webrequest has allow scene activation
Presumably AsyncOpertion was originally used only for scene loading so it's a holdover from then
Im using a cloth componenet on a low poly mesh and it becomes smooth shaded, how would I "undo" that shading and still use the flatshading as if there was no cloth componenet
shading should look like the picture to the left
Hello, I tried to code a game with AI. I don't know much about coding; I'm still learning. I encountered an error while writing the FPS view. Actually, it's not really an error, but something I don't wantโthe player moves while turning left and right. If anyone can help, I can send the code.
I hope I have been able to explain my problem.
hi i am a newiebide , i wanr to ask that - is chat gpt a good teacher for learning unity , as they have introduced a new method called study method
Based on my experience, it's a very bad idea. Right now, I'm suffering because of it.
In my opinion it is a tool, if you're stuck it might help you progress and eventually find the problem
I'm stuck right now. No artificial intelligence can solve it, or maybe I can't explain it.
You want structured learning already made. Asking an AI to help without knowing correct terms wont do much good
Im at the same right now ;p
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
Shocker group of 3 people came for help at the same time cause their oh holy ai failed them ๐
Isn't that funny, HAHA?
If you want help send the !code and explain your problem https://dontasktoask.com/
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
or leave the server not like it affects me :/
More like, no information on the particular issue on unity forums and the AI could explain it either ๐
I was working on a project again and found that it seems to have stopped working. I have a door button that when you click on it the door opens, the button is a gameobject. It has a collider and it has a rigidbody. The script works when it isn't kinematic but it starts floating away. How can I stop it from floating away
Is there a reason why the button is physics based?
Attach it to something with a joint.
But yeah I would avoid a physically simulated button at almost any cost.
No its not
Only time i would understand it is if it's a game like human fall flat and you push the button with the character
You have a rigidbody on it so it is
And how would I make the button work without rigidbodies
cause it only worked when I gave it a rigidbody
Animation
even then
That works when you have a collider, not a Rigidbody
you need to explain how your button works
we can't really help without understanding that
you hover your mouse over it you click it triggers an event in another script
that's all
not sure what else I can explain
There's no need for a Rigidbody for any of that
Sharing the code would do wonders
Also you can/should use IPointerDownHandler not OnMouseDown
OnMouseDown won't work if you're using the new input system, for example
is that with the old input system
I'm on old
it works for both
and any idea why this isn't working
not really other than some other object is probably blocking it
but OnMouseDown is really not debuggable
other than - it's working or not working
Honestly couldn't say i would've just gone the route of a raycast
also is this a first person game?
that'd do it
thansk both of you
next thing I need the onmousedown for I'll use onpointer instead
or raycast
Event System + IPointerClick is the best
does require a physics raycaster/physics 2d raycaster to work with colliders however
lately I've been using IPointer but for this it's a tutorial I made a while back and adding some content to it so I don't want to change but I will mention the IPointerClick when making new stuff
The main benefit of using it is that you get the "is blocked by UI" stuff for free. Basically it interacts properly with other mouse interactions in the game.
i have a very basic question ๐
obviousely if you want to make a game you will encounter the problem of how to move gameobjects. often times i have been doing it with transform.position += transform.forward * speed * Time.deltaTime; but i know there are also other ways to do it. my question is; what is the best way to do it if you want to have the best performance.
it's really not a performance question
it's a question of how do you want the things to move?
DO you want them to collide with things?
Do you want physical realism?
Do you want them to move on a curve?
Do you want them to move blindly in a direction, or towards a certain waypoint
etc
ok, well what is the best way of doing if i just want a gameobject moving in a straight line until he runs into a range which is defined by a trigger circle
Wait, is this function real? If not then why does it appear in the IDE? There is FindWithTag already
Does your object have a Rigidbody?
As it says you need to provide the tag as a parameter
Then you should move it via the Rigidbody
if the body is dynamic (not kinematic), just set its velocity
if the body is kinematic, use MovePosition in FixedUpdate
are you on unity 6.2
Yes, I can provide a string and no error occurs
Yeah
Exactly
it's not saying it doesn't exist
it's saying you didn't provide the parameter
no no their asking no api result
when you provide the required parameter, it's happy
https://docs.unity3d.com/ScriptReference/GameObject.FindWithTag.html It got renamed in 6.0
but the old one is still there. Docs only have the new name
So they have 2 copies of the same function now?
more specifically it seems they dont index the old one on the search
Eh, that's odd
the old page is still there
they're going to deprecate the old one
docs do have the old one, it's just not indexed
so
rb = GetComponent<Rigidbody2D>();
rb.velocity = Vector2.zero;
right?
which is kinda strange tbh
ah whoops
thanks man ๐
not really, the search results isn't exactly enough space to mark deprecation well imo
sometimes i don't look at docs page and just do search or browse the class page to check spelling (for example)
i mean yeah but in this situation
search old one -> click page -> says deprecated
search old one -> no result -> gaslit confusion leading to questions here
i'd be getting to use deprecated functions in this scenario
and doesn't the ide also report deprecated stuff (and put it low in intellisense) anyways
not recommending deprecated/obsolete things is a good thing, actually
why do i get forced to use linearVelocity instead of velocity?
thats what its called now
Because it was renamed
Yes
how do i make a new transform out of a rotation, position, and scale?
You can't really make a new Transform without creating a whole GameObject. A Transform is a Component on a GameObject.
What are you actually trying to accomplish?
If you just want a place to store those things you can use Matrix4x4 or just Two Vector3s and a Quaternion.
Are you trying to just set the position, rotation, and scale of an object?
{
StartPosition = transform.position;
StartRotation = transform.rotation;
StartScale = transform.localScale;
}```
i did that, but how do i make it so the start position, ect, are only set once, because right now the transforms position and the variable are like, linked amd updated every frame for some reason
wdym by "the transforms position and the variable are like, linked amd updated every frame"
those three variables are only set one time in the lifetime of this object unless you have code elsewhere assigning to them
I'm not. when the transform position changes thevariables change too
They will only be set once right now unless you are updating them in Update
prove it
Start only runs one time.
The three are value types (not reference types). The values will only be copied during Start
Basically you need to show us the rest of your code and explain why you think it's being updated continuously.
gimme momnt rq
oml im sorry for wasting yalls time i was setting it later in the code
hello, please help me im about to go bald.
OnCollisionEnter is never called: both gameobjects have colliders, both collders are NOT triggers, both have rigidbody kinematic. and one has that script to listen for OnCollisionEnter. both on the same layer too
i do not get why
both have rigidbody kinematic
there's your issue
how can i then listen for collision without collidingg?
...think about that for a second
they can't collide if they cannot collide
i was using trigger, but i need to get contact point, and trigger doesnt provide it
there is no contact point if there is no contact though
if something goes thru a wall of the level
they are not physically colliding. therefore there is no collision.
how do i get contacct points i need it
for what reason
to show particle
and do these objects need to physically collide
sometimes yes sometimes no
okay so at this point you should provide more actual details so a proper solution can be provided because i don't enjoy playing 20 questions just to get some basic info
for instance, i have a sword, i need it to particle on point of collision
but i do not want any rigidbody physics on it
because its held by character
use a boxcast
or Rigidbody.SweepTest
i tried Physics.ComputePenetration, and collider.ClosestPoint but both are rly bad
is that better?\
yes
there is no better
they do different things
look at what they do and decide what you want
yes, in this case
both terrible tried em
problem is they cannot infere the correct direction
yes they can
the normal is contained in the RaycastHit
it has all the info you need
Physics.ComputePenetration does exactly what it says, I've used it many times with no problems.
But for sword swinging, I would use a sweeptest or raycast. A sword slice contains many points of contact, each with a different normal direction.
yes im doing raycast currently. its not very stable though
especially with non linear shapes of swords
raycast doesn't make much sense to me vs boxcast here
You have to do multiple raycasts, along the sword, if you want an accurate result. Sweeptest or boxcast don't let you put in an angular velocity.
you would/could do one baxcast each frame during the animation, tracing out the full path over time
which would account for the rotation part too
There's GIFs in here that explain what I mean
https://mordhau.fandom.com/wiki/Tracers
Between each frame, the box in the boxcast can't rotate though. It can only move in a straight line. If you don't have enough frames, you won't be able to capture the movement of the sword accurately, especially if it's a very long sword.
if you don't have enough frames then you wouldn't be able to render accurately even if you could detect accurately
So what?
This is a simulation. A crude simulation.
The physics engine works in discrete timesteps too
it's not meant to be 100% accurate nor does it need to be 100% accurate
As for frame count you'd use FixedUpdate so the framerate of the game wouldn't affect things anyway.
none of the other mentioned approaches are 100% accurate either
Just to better illustrate what I mean
yes understood - although you can break that down into arbitrarily as many steps as you desire
nothing limits you to one boxcast per frame
We don't know how fast their sword is going. With the default 50 FPS fixed tick rate, it doesn't have to go very fast to get these large gaps.
you can just rotate the box in frame 2
you can pretty easily make that a configurable parameter
True, sub ticks is another solution to this. The raycast solution doesn't capture the sweep of the tip accurately.
like however the visuals are, rotate the box correspondingly
The two boxes represents one boxcast. You can only specify one rotation for a boxcast.
It might be better to pick the average rotation between the two frames, if you want to do one boxcast per frame.
this breakdown is also possible (ignore the text, ChatGPT generated this image)
and yes those boxcasts are not accurately rendered - they'd be smaller squares bascially travelling along those paths
When creating a system for the player to be able to pick up and discard weapons, if there a typical way to making it? As in, should I instatiate a weapon at the players hand or keep the weapon always there but disabled, and enabled it when it's appropriate
Your choice.
I'm trying to make my first game right now with the first person controller starter asset but there's a hidden code somewhere that's hard locked the far clipping to 500 and I can't find it in the scripts. I can see an override in the nested player unpack prefab but I can't even change the override. any ideas?
some one please help me i m stuck with this
when i press a d or s for direction the movement glitches and everything is fast
you have both a rigidbody and a character controller that are fighting for control
you can't have both
decide which one you want to use and remove the other one
(if you choose character controller you'd also remove the collider, since that's for the rigidbody)
I see
and if i use rigidbody then i just have to remove the character controller right
and also change any code that might have been using that
any ideas for the issue I'm running into?
just above Ryushio's
this one
which far clipping are you referring to exactly? on a camera component?
yessir. end goal is 4000 far clip and I'll later utilize LOD for performance.
what do you mean by "locked" exactly?
locked as in I can change the value, but hitting enter reverts the number back to 500 in both the camera component and the override page under the nested player unpack
still reverts to 500, regardless of the value. I checked the scripts in the starter assets folder, nothing in there mentions far clipping either. I'm at a loss with it
what about 499?
same thing
none of the scripts mention farClipPlane?
the starter assets use cinemachine, no? so it would be a setting on the vcam not the camera itself
@naive pawn Now my player is not jumping only the animation plays.
were you perhaps using charactercontroller to do that before
also no need to ping me again
just post your issue
well there's no jump method, no
you just apply an impulse to make it act as if it were jumping
rigidbodies don't know about jumping, you just tell it what to do in physics terms
you haven't really provided any info to go off of
perhaps show the !code that is meant to make you jump
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
nope, see above
Am I doing something wrong here with trying to detect the F key in a For loop? The gun is detected so the first For loops works, but nothing happens when I press F so the second loop doesn't work
// void HandleJump()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundCheckRadius, groundLayer);
if (isGrounded && Input.GetKeyDown(KeyCode.Space))
{
rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z); // reset y before jump
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
void OnDrawGizmosSelected()
{
if (groundCheck != null)
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(groundCheck.position, groundCheckRadius);
}
}
see !code
๐ Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
๐ Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
are you sure the method is even being called? debug at the very top of the method before any conditionals
might be your raycast not hitting anything
also what for loop
Sorry, I meant If loop
A tool for sharing your source code with the world!
This is the code ^
The racast is defo hitting it because the Debug.Log is working
I checked:
CinemachineVirtualCamera.cs
CinemachineBrain.cs
UniversalAdditionalCameraData.cs
FirstPersonController.cs
CinemachineBrain.cs was the only one with code referencing NearClipPlane and FarClipPlane, but none of that code explicitly sets far clipping to 500 as far as I can see.
if ((state.BlendHint & CameraState.BlendHintValue.NoLens) == 0)
{
Camera cam = OutputCamera;
if (cam != null)
{
cam.nearClipPlane = state.Lens.NearClipPlane;
cam.farClipPlane = state.Lens.FarClipPlane;
cam.orthographicSize = state.Lens.OrthographicSize;
cam.fieldOfView = state.Lens.FieldOfView;
cam.lensShift = state.Lens.LensShift;
if (state.Lens.ModeOverride != LensSettings.OverrideModes.None)
cam.orthographic = state.Lens.Orthographic;
bool isPhysical = state.Lens.ModeOverride == LensSettings.OverrideModes.None
? cam.usePhysicalProperties : state.Lens.IsPhysicalCamera;
cam.usePhysicalProperties = isPhysical;
if (isPhysical && state.Lens.IsPhysicalCamera)
{
cam.sensorSize = state.Lens.SensorSize;
cam.gateFit = state.Lens.GateFit;
cam.focalLength = Camera.FieldOfViewToFocalLength(state.Lens.FieldOfView, state.Lens.SensorSize.y);```
try debugging the values you're checking - isGrounded and the GetKeyDown call
show what you are actually changing.
ok
right, but it's setting the camera values to the cinemachine's own values
you would need to modify the cinemachine stuff instead of the camera's values
so you remember how i said you need to change it on the vcam not the actual camera?
yeah but the vcam doesn'
notice how at no point did i say you needed to look into cinemachine's code, just that you need to change the setting on the cinemachine virtual camera