#💻┃code-beginner
1 messages · Page 637 of 1
woahhhh. let me try this out!
basically involves following the patterns from above, and using it for rotation
(pattern being: Get Input on Update/LateUpdate --> Consume it for Physics in FixedUpdate)
ohh that might be good for my project too

using UnityEngine;
public class PlayerLook : MonoBehaviour
{
public Transform cameraHolder;
public float sensitivity = 2f;
private float xRotation = 0f;
private void LateUpdate()
{
float mouseX = Input.GetAxis("Mouse X") * sensitivity * Time.timeScale;
float mouseY = Input.GetAxis("Mouse Y") * sensitivity * Time.timeScale;
// Rotate the player body (horizontal rotation - yaw)
transform.Rotate(Vector3.up * mouseX);
// Rotate the camera holder (vertical rotation - pitch)
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
cameraHolder.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
}
}
Mine's like this, have a separate cameraholder object
yeah but make sure to read the documentation:
Changing the rotation of a Rigidbody using Rigidbody.rotation updates the Transform after the next physics simulation step. This is faster than updating the rotation using Transform.rotation, as Transform.rotation causes all attached Colliders to recalculate their rotation relative to the Rigidbody, whereas Rigidbody.rotation sets the values directly to the physics system.
this means that this would also need to change:
Vector3 moveVector = transform.TransformDirection(keyboardInput) * speed;
```with
```cs
Vector3 moveVector = rb.rotation * (keyboardInput * speed);
yeah this is option is common/recommended when using a CharacterController instead -- when u don't really use FixedUpdate (or Rigidbodies)
private void Update()
{
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
{
this.transform.position += Vector3.left * this.speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
{
this.transform.position += Vector3.right * this.speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
{
this.transform.position += Vector3.up * this.speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
{
this.transform.position += Vector3.down * this.speed * Time.deltaTime;
}
}
This is my movement for my character,
is there anyway i can set this so once a key is pressed it switches to a different sprite / animation?
https://paste.mod.gg/jlqaaeiyorsg/0 i think i did everything. can you check it out? also it doesnt jitter anymore. thanks a lot bro!! your a life saver
A tool for sharing your source code with the world!
yea, you can reference the animator for that character
but you also have to set up the animator controller itself
there's a potential bug hm
you better do: if (!wantsToJump) { wantsToJump = Input.GetKeyDown(KeyCode.Space); }
and consume with: void Jump() { AddForce(); wantsToJump = false; }
there is a lot of bugs like them hahhahaha. the x rotation isnt even clamped.. i wanted to get the jitter over with first. i will add a jumpcooldown
i dont know how to thank you man. your genuinly a life saver
also, imo try to write AS FEW LINES OF CODE AS NEEDED first while working on the thing
as in, while prototype, your 70 line-long script could be 15 lines
then you could spend some additional time to clean it up if you feel it grows
np 🙂
btw this is for much later, but if you want to do something like camera bobbing while running
once you get to that point, switch to cinemachine - trust me
also protip -- don't trust the "trust me" source 😆 try for yourself if you're curious otherwise it's fiine
well yea 
i aint going that advanced lol... like you said ima walk first before running... thanks a lot though!
I personally found cinemachine limiting my gameplay 😛 (at least as gameplay camera) -- but for cinematics it's nice to have
wth 😭
oh i see
it's actually super nice, I was able to get quite a simple camera bobbing function with it
without it, it gets super complicated as you'll have to lerp some values etc
ohhh
for example when you have it like that it's more apparent where the issues might be: https://paste.mod.gg/fddvaypcuegx/0
hmmm wrong ling again? there, fixed
here the only issue is that camera rotation likely won't be smooth enough, because it's done in FixedUpdate (which updates less frequently)
woahh..
oh i see
however i do like have things more organized. functions makes things organized ykwim
the thing about functions is that you only really want them if you know that you're gonna reuse them somewhere
(usually)
you can do organizing with comments for the most part
mostly because:
- You have one-line functions taking 3 lines
- Your functions aren't ordered by time-of-execution
hmm true
for real.. should i practice the habit of less functions as a beginner?
it's a good mindset to have with splitting logic into functions -- but splitting one line into its separate function isn't really proper
especially if it's NOT a function you're going to reuse
imo you should practice the habit of AS FEW CODE AS POSSIBLE as a beginner
each function should have a specific action
whether that leads to fewer functions or more is secondary
alrighty
hmmm i see
thanks a lot guys! i dont know what i'd do without you all
mainly because less code is easier to work with. Once you have the system fully ready and tested, you can reorganize it if you feel like it
np gl hf
honestly though i think Jump being in its own function is fine. it lets you easily find it to apply other logic in the future if needed, like animations or ground checks or cooldowns.
but MyInput, MovePlayer, MoveMouse don't really need to exist unless you get more specific with them
why does SceneManagement does not show to my script? i even put the name space of using UnityEngine.SceneManagement; but...
wdym doesnt show to my scrpt
well the error said
Assets\GamePlay.cs(9,9): error CS0103: The name 'SceneManagement' does not exist in the current context
show the entire script
_
_
that way I could not use SceneManagement in a function
using UnityEngine.SceneManagement;
public class GamePlay : MonoBehaviour
{
// Start is called once before the first execution of Update after the MonoBehaviour is created
void LoadScene()
{
SceneManagement.LoadSceneAsync("SampleScene");
}
}
SceneManagement is not a class
it's a namespace
SceneManager is a class under SceneManagament namespace
OHHHHHH I DID NOT NOTICE THAT
private void FireWeapon()
{
readyToShoot = false;
bulletsLeft--;
if (recoilScript != null)
{
recoilScript.Recoil();
}
Vector3 shootingDirection = CalculateDirectionWithSpread();
GameObject bullet = Instantiate(bulletPrefab, bulletSpawn.position, Quaternion.identity);
bullet.transform.forward = shootingDirection;
bullet.GetComponent<Rigidbody>().AddForce(shootingDirection * bulletVelocity, ForceMode.Impulse);
StartCoroutine(ResetShooting());
}
``` @swift elbow
what obj did you reference for bulletSpawn ? show your inspector
its literally selected
ok show me
show your whole script and recoil script
a little off topic, but you should be calling your recoil function after the bullet is shot, not before
!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/, https://scriptbin.xyz/
📃 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.
https://scriptbin.xyz/uzicarajaj.cs its not full script but u dont need to see reload burst and inspector stuff
Use Scriptbin to share your code with others quickly and easily.
Use Scriptbin to share your code with others quickly and easily.
i dont see anything wrong. have you debugged the positions of the bullet when it is spawned vs the position of where it's supposed to spawn?
also, is this AI?
these comments reek of ChatGPT written code
recoil is
so is the other one
obv not if youre having problems
unfortunately in this case it doesn't as most people here aren't interested in helping people using ai generated code
look
only recoil is ai
both of them very obviously are
its not
it's just against the rules
issue isnt even in script he just asked me to put script and main script isnt even ai generated
so it's not code issue?
its just duplicating bullet mesh to bullet spawn how can it be code issue
then why are you posting this in code related channel?
he asked me
The original question seemed pretty script related
You seem to be spawning the bullets at the wrong place
it doesnt follow bullet spawn
why does that happen
Try logging the position of bullet and bulletSpawn right after you spawn it. Do those numbers match?
ofc they dont
thats the problem
u can see that bullet spawns in same place as non recoiled gun
What did the logs say
but gun has recoil
wait lemme try
You should also check that the bullet's visuals aren't offset weirdly or anything.
(maybe don't say of course if you haven't tried)
no it leaves mark
when it hits walls
If you haven't done it yet why did you say the logs matched
i said opposite
Sorry, still, same question. Why did you say you checked the logs if you didn't do them yet
If you want help on the internet it's usually best not to directly lie to basic debugging questions
because its obivious
But they do match
in programming nothing is obvious
So obviously it wasn't obvious
one is at 353 and one is at 0.56
Well if it was so obvious they don't match, care to explain why they do
353 is rotation lol
You're looking at the rotation
You don't even know what logs you're writing
oh
Oh man did even these logs come from chatgpt
i read it incorrectly
I can't help someone who just directly lies when being asked questions and can't read their own code I'm out, have fun
I got better things to do with my time than wrench answers out of an unwilling subject
i do bruh
anyone know why Instantiate isnt working ?
A tool for sharing your source code with the world!
Start by reading the error message
Your main issue seems to be that your script is not a MonoBehaviour
youre not deriving from monobehaviour?
im being gas lit by c#
Since you're not deriving from MonoBehaviour you would need to write Object.Instantiate here
PraetorBlue said it first, im a fraud 😔
but yeah seems like you meant to derive from MB
clearly it doesnt if you spend 1+ hour trying to fix it
you could have rewritten it properly, no jank ai, in the same amount of time and actually end up with working code
oddly enough, the AI code was right. it was just a user error
they were given correct code but thought there was something wrong with it lmao
gottem!
the contrast to trusting ai to write the entire class, but not trusting it enough for it to be error free

just the entire class? i let it write complete libraries for me 😁
i dont know issue tho
its just camera moving up in sync with bullet
Show your bullet prefab
thats fair, but this is a key issue with ai code. it writes an entire block of code at once, so if theres a problem inside that, it will be hard to find it
had you written it from scratch, testing it out along the way as you write it, if an issue appears early on, you'd have a better chance of fixing it
And positions of its children
i didnt write it from scratch
i took it from yt tutorial
and told it turn it into text
then it had bugs and it fixed it without problem
im talking about recoil script
also i think problem is in void start
There is no way to put a frame-by-frame (flipbook, spritesheet) animated image in uGui? 🙃 (didn't check toolkit)
I already coded my own, but I am wondering if I just failed at google and there is an "animated image" behaviour or something 🤔
can you explain what it is thats going wrong exactly? ive tried following earlier messages and im not on the same page here
Still does not show where the actual pivot of the bullet is. I don't see if you re in Pivot or Center gizmo mode
it saves position in void start and then it goes back to that after shooting
well, is that not what you want?
initialGunPosition = gun.localPosition; // Save gun's initial position
this is caching the position, presumably so it can be restored back to it later on
pivot is in center i think
You selected its child
you have the Tool Settings menu hidden. Press the ~ key and turn on the Tool Settings menu.
This button will turn it on too
It's kind of funny how adamant you were about making the tank treads as ludicrously realistic as possible and then when it comes to bullets your prefab is just the entire cartridge like someone who's only seen guns in cartoons
unless u plan on shooting it at slingshot speed he'll never even see that little thing 😄
what do u mean
He means you don't know how a bullet works.
You seemed so committed to military accuracy, then your model for the bullet is the whole cartridge. Including the bit that's just full of gunpowder that will literally explode in order to make the bullet go
just throw zero-g oranges ;D
30% more bullet per bullet
this one doesnt matter
im trying to make it look like csgo
Neither did the last one
it did
i tried unrealistic way u offered me
it didnt look good
i will finish that one too its just constraints connected to connectors
Hey folks!, I am trying to practise using Line renderer and I just have very basic 2 3d spheres in my scene and I want to draw a line between them. But I keep getting "Object reference not set to an instance of an Object" at line " lr.SetPosition(i, points[i].position);".
Can anyone please guide me to achieve my goal.
public class Line_Renderer : MonoBehaviour { LineRenderer lr; Transform[] points; private void Awake() { lr=GetComponent<LineRenderer>(); points=new Transform[2]; } public void setUpLine(Transform[] points) { lr.positionCount = points.Length; this.points=points; } void Update() { for (int i = 0; i < points.Length; i++) { lr.SetPosition(i, points[i].position); } } }
When do you call setUpLine
I am calling it from another script thats added to the main camera
~~I believe points=new Transform[2] initializes a new array, but it won't be populated. You need to set points[0], [1] and [2] with references to transforms. ~~ nvm
is your lineRenderer assigned?
So your first script is probably running before this one, and points is null. You will want to ensure that array exists before you try to use it
Or rather, the positions array you create from it
why do you even create a array of point in Start()
Since you do have an array, it's just full of nulls
just use the start and end you've assigned in the inspector
what do you need the array for
It's also worth noting a Transform[2] will contain 3 elements, starting with index 0. So even if you populate [0] and [1], you will have an empty (null) element at index 2
Actually I was getting the same Object reference not set error for the Send_Transform script as well which is added to the main camera. After I Initialized it in the Start(), the error did not occur for this script
ohh Thanks for letting me know. I will fix that
Nah, Transform[2] will have 2 elements, you are overthinking this
Gah, I had a feeling I was
No, that constructor takes a size, not last index
Actually I didnt really understand why the Transforms need to be sent from the script on the main camera from the tutorial video i was following on youtube.
But How can I make sure my Send_Transform.cs runs before Line_Renderer.cs script
no what
I'm a little bit sleep deprived over here, forgive me
Would it not be easier to just make your Transform array public and assign your start and end point in the inspector, in your case?
yea like it's tottaly super bad design
why are you making a separate field for each transform
and then make a array from these transforms in update
when you can make a array, exposed to the inspector and just drag&drop the transforms you want
imagine you will want 5 points, you'll make point1 point2 point3 ... till 5 and then make array out of it? what if you want 20 points?
I'm not entirely sure why the Send_Transform script _exists.
You set both values to itself, and they never change even though you keep sending them every frame? Honestly just delete this script and make the points array public or serialized in your line script
Hope you dont mind, I am complete beginner and Now I have removed the Send_Transform Script and I have assigned the Start and End gameObject from inspector. But I still keep getting "Object reference not set to an instance of an Object"
This is my inspector
You are still overwriting the points array in your awake method, and in your setUpLine method (in case that is still being called from somewhere).
why are you overcomplicating it so much
- make a public/serialized array with your transforms
- pass that points to the line renderer
I could be wrong, I don't ever want to dunk on a beginner for no reason, but this does give the impression that "vibe coding" was used to create the framework and the desired function isn't as well-understood as it could be
starting from scratch on this function instead of trying to fix what it currently exists as may be easier
you don't need the pointsCount field aswell
I don't think there's any AI involved in this case
Your code is still setting points to an empty list in Awake. If you check the inspector when you hit play, you'll see it blank out. If you're setting it in the inspector, you don't need to set points anywhere, and you can move the positionCount line from setUpLine into Awake and delete that function as well
Nah, not enough pointless comments to be AI
with all the respect but even chat gpt wouldnt make such stuff
None of the hallmark
//Add two numbers together to get the result
int x = 3 + 7;
Guys Now its working 😅 🫡
read back in the thread a bit and yeah, I retract my statement
I do maintain that starting from scratch and reworking the function to be less convoluted would be beneficial
Finally understood I dont need to initialize array if I am setting it from the Inspector.
guys does anyone have a good video for making a ui?
define making a ui
as it currently exists, you don't have a snowball's chance in hell of understanding this code if you go back and read it again to make a change in a week and a half
ok im trying to have a little screen of text saying how to play and then i want it to close when u click a button
UI gang over at #📲┃ui-ux might have some suggestions
just watch some basic unity tutorials, it's super basic
if you know the basics of how to get objects to display and use scripts, it's pretty easy
Use a sprite with an unlit shader, usually attached to the camera
yeah i dont think im good enough with the basica
what
back to tutorials for me
he just want's a UI text, not a sprite
just add a canvas, add a text, add a button, you'll get it, it's not black magic
he said he wanted a little screen of text saying how to play, for single popups like that I typically use a sprite object over a canvas, but either would work
Or attach it to the camera
I'd use the sprite for the pane, and a textmesh to display the actual text
And attached to the camera assuming this is a first person camera controller
It's what I was taught in my initial unity class and as I say this I'm realizing that goes in the "my proffessor was unhinged" bucket and not the "this is fine and normal" bucket, oops
still trying to adjust, that class was useful in some ways but very wonky in others
you'd use a Sprite for a background and a UI text to display content of that panel?
Definitely relatable
that's a felony loll
For the project we got a .png with a blank pane for the text box and were told to put text in there, it didn't specify how in the reading so he told us to use a sprite renderer
change your school bro
UI is usually just drawn to the screen in the most basic form. You will rarely need to attach it to a camera in 3d space outside of cases like VR, where you need it in worldspace.
Image exists for a reason
don't use Sprite for UI stuff
unless in some rare edge cases
Out of curiosity, what's the difference there?
I believe you, definitely, I just don't know the difference off the top of my head
maybe he told me that because I mentioned wanting to make a VR game, but more likely he was just unhinged
EAUGH
Ugghhhhh okay I have a STORY for you
my first job out of college was working frontend web design for a nuclear power plant (yes this is real)
Nah, attaching it to the camera is exactly the pointer I'd expect someone to give to someone wanting to make UI for VR.
you can make World Space canvas, it doesnt have to be Overlay
definitely stop using Sprite Renderer for UI stuff
one of the team members was assigned to make a header for the generic web-app template, and instead of making it SCALABLE like a normal human he made like ten different bespoke hard coded headers in different sizes, aspect ration, logo variants, etc, and had them assigned by their index number
you wont be able to achieve different sizes, aspect ratios, scalable panels etc with Sprites as a UI either
unless you make some shananingans in the code
O(n), technically...
would a world space canvas render on top of geometry that's between the UI and the player's eye?
it's just like any other object in the world space
you can move it, rotate it etc
place it in whatever position you want
I've played VR games where if you hold an object between the UI and your face, the UI renders on top of it but still looks farther away to your eyes, the parralax frickery gives me a headache and I'd prefer to avoid it, unsure what specifically causes it or if it's some specific choice
I'm trying to upload game on web but its giving me error "are you missing and assembly reference"
Well... are you?
idk I started coding 2 days ago lol
what is it anyways
tried searching but i didn't get any help
The first step is actually reading the entire error message
You started coding 2 days ago and are already trying to upload a game to a website💀?
private void tween_camera(Vector3 axis) {
System.Action<ITween<float>> circleRotate = (t) =>
{
transform.rotation = Quaternion.identity;
transform.Rotate(axis, t.CurrentValue);
};
float startAngle = transform.transform.rotation.eulerAngles.x;
float endAngle = startAngle + 90;
// completion defaults to null if not passed in
transform.gameObject.Tween("RotateCircle", startAngle, endAngle, 0.35f, TweenScaleFunctions.CubicEaseInOut, circleRotate);
}
```Heyo, I have a tween library, but I can't seem to figure out why it doesn't work properly if i remove the```c#
transform.rotation = Quaternion.Identity```I'm trying to rotate on top of the current rotation, but the identity resets the rotation that's why I tried removing it, but it breaks the tween completely
Yea
When I upload the game i will let you try it out
but i'm getting erros
The only peice of information you have shared is that you are getting a vague error message, that's not something actionable
Error building player bc scripts had compiler error?
have you tested or run your game at all?
my scripts don't have errors tho..
did you build the game, or are you trying to put a unity project file into a website
Ofc i did
I can't build the game bc it gives me error
You said the error came from the website
you need to build a game before you put it on a website
it would also help if you mentioned which website
No I'm not uploading it to a website yet. I'm Currently getting error trying to build the game.
Elaborate on this please, what do you mean?
I meant error in console while trying to build the game
"are you missing and assembly reference"
this isn't the error message, it's just a tip on what to look for.
the error message is before that
it would also help if you mentioned things like
- is this a project you made from scratch or is it a modified tutorial project
- what version of unity
also for future reference, please don't retype errors or code, copy them over directly
I had using UnityEngine.Android i think thats why
Copy?
How would one go about making a lap system for a racing game that logs what lap the user is in when they pass through an object
Sequential triggers
genius
I tried that It didn't work
do you not know how to copy and paste text?
Ofc lol
So try it
ok, wdym it isn't working then
U highlight it from the bottom box the extra details after clicking the error
Ok ok currently its building
let me see if i get any errors then i copy
I heard uploading on itch.io is good?
make a collider, no mesh or physics, set it up to run a function when the player's collider passes through it
in some kind of game manager script
public int lapNumber
playerPassedThroughTheThing()
{
lapNumber += 1
{
It's the simplest solution.. the only issue I see with it would be being able to reverse around the track backwards to trigger one
That wouldn't give u an advantage so not sure if that's a deal breaker lol
Drives forward and backwards over finish line 10 times
thats a tough one
If you currently do not know how to do things like copy and paste text, I'd say you're getting ahead of yourself. I would reccomend taking some kind of computer fundamentals course to get more familiar with your machine, and start with basic personal projects.
I understand the urge to upload your work and share it, but it's exremely unlikely bordering on impossible that after two days you've created something worth the time of someone to play and give feedback on. Game creation is a complicated process, and reviewing for education is a very different prospect to actual sharing with the hopes of getting feedback as a game creator.
not really, you just have some trigger colliders around that are required to be hit before you add to the lap counter. when you add to the counter, reset whatever method youve chosen to indicate that they were all hit.
Do keep working at it, but picking smaller short-term goals is important in the early stages of learning programming.
I have an issue where my objects bob up and down and move wierdly without any applied forces on fps lower that 144 . I think this these lines r the problem . Any advice on how to fix. Lines-void Update()
{
transform.rotation= Camera.main.transform.rotation;
}
is this code on all objects? Why? where is this script attached?
yes its attached on all the props. Im making a doom-like so i need all the sprites to be billboarded
this is great that you said this
it works perfectly fine on 144+ fps but is completely broken on anything below
you could probably get away with just having one halfway down the track, depending on how much time you want to spend on it
you guys are geniuses thank you
do your objects have any physics objects attached?
yes
I followed a tutorial now I'm done and i did learn a lot of things I ended up making a simple game not too advance. I just wanna know how to upload for future use and dude I know how to copy and paste that is a common thing 😭 . I also have experience on building games and scripting, I'm tryna learn C#
i'd put 2 triggers then
one right before the lap
have an invisible wall right before the lap as well
are you rotating the entire object or just the sprite component?
only deactivate wall if player passes first trigger
entire component. also when i disable the phyic material it actually stops when no forces are applied. but when i do apply a foces it overreats and starts bobbing and mvoing uncontrollably
I would try altering the structure of your objects so that the core parent object with the physics component does not rotate, and a child object that holds the sprite component does rotate. You can also use the rotating component to do things like emit projectiles.
Rapidly rotating physics objects using transform.rotate, essentially teleporting, can cause a lot of things like that
let me try
i did that and now the issue happens on all fps limits
Consistency is improvement, at least! can I get a screenshot of your object heirarchy?
this is the objects parent
this is the child
the pickups script manages the rotations
if you turn off the pickups script with the checkbox, does it still jitter?
no it doesnt
it only jitters when this line is present
can your camera look up?
either way, try only using the horizontal axes in the rotation, instead of the entire transform.rotation
nope my camera cant look up. also i have used quaternion.euler(0,camera.main....,0) but the issue remains
!docs
Well, that's very strange... have you tried lookAt?
I just finished a script of mine, anybody care to look over it so I can get rid of some bad practice?
i fixed it by putting it in fixedupdate instead of just update. since the framerate seemed to be the issue
physics is wierd ig
Oh, damn, I forgot that Update() is the default
I always add fixedUpdate by force of habit at this point, I forgot to even ask
we can't look if you dont post it 😅
hey can somebody give me player movement code for a capsule
Sure, somebody can. That somebody is you, after visiting !learn and figuring out how to make code all on your own
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
this is very simple, a trillion tutorials online for this it's at the beginning of most beginner tutorials
ok
please don't crosspost
I realized it didn't fit into this channel Sorry
This is my mouse look script I'm remaking my fps controller again. How can I rotate the camera up, down,left,right?
https://paste.ofcode.org/DwWHEWDXkmLCCSnzxcfVbB
generally you would have the camera pitching (with similar logic as your rb rotation, except with y) and then inherit the rb's yaw
(since it's on a transform instead of an rb, you could use Translate.Rotate with the delta instead of applying the delta to the existing rotation; or you could basically have the same code but with localRotation instead of rb.rotation)
Do I update the camera in LateUpdate? I heard you do it in late update as my player has a rigidbody and the camera is not a child of it
sure, lateupdate works
sorry I keep bothering you, Do you know any tutorials/sources that go over this? tbh I'm just confused on how to do this part and I do not want to mess this up.
which part exactly?
Rotating the camera in any direction with the mouse like a normal first person camera. I don't want to really get anything wrong.
Hi, I am planning on starting my 2nd game. I created my first one about 3 years ago. So lost about all knowledge I had. I also wanted to introduce a friend to it. Do you guys happen to have a really good and all-round "tutorial" about how to start with Unity and everything linked, accounts, preparation of your project, publishing your project etc? Would be really helpful instead of just blindly going into it and having a ton of errors afterwards. Thanks already! 🙂
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Oww interesting, thanks will check that out!
I had a question about object movement. If I am facing one direction and I press W it will move forward but then if I look to the opposite direction and press W the object goes backwards. How do I make the object go towards the direction I am facing?
This is how I have it setup.
sounds like it's just going the same direction regardless of where you're facing
are you rotating the object that the movement script is on, or just the camera?
also, 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/, https://scriptbin.xyz/
📃 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.
Don't use Vector3.XXX; this is based on the world position of (0, 0, 0). You need to use the direction the object is facing (based on its axis). If this is 3d, typically, it's transform.forward. If not, use the appropriate axis based on the object's forward-facing direction . . .
From your description it's working exactly as you describe
transform.Translate moves in local space by default
so I think the Vector3.xxx things are correct here
the question is - which object is actually rotating here? Is it the one this script is attached to?
Or a different one?
a question but ive noticed limiting fps in unity leads to void update working differently
Update always runs once per frame
if your framerate is lower, that means fewer updates per second
that is all
it never does anything other than running exactly one time per frame
yea thats what i though but when i limit fps it runs every frame of the orignal unlimited fps
no it runs once per frame, period.
I am using freelook camera
The camera is the only thing that is rotating the object doesn't rotate
then you want to move the object based on where the camera is looking
not where the object is looking
You need to get a reference to the camera and use the camera's Transform to determine which direction to move
You can usually get at the camera with Camera.main
yes but im getting odd results when trying to set a position of one object to a another using heldObj.transform.position = holdPos.transform.position;with uncapped fps or even with vsync it works just fine but as soon as i limit fps with code it seems thats it is always a few frames behind. this gets fixed when i use fixed update instead of update in low fps but then it become broken on high fps.
Same thing if I am using cinemachine ?
you would need to show your code and explain what components are attached to all the objects etc. Basically, show what you tried.
CInemachine is irrelevant here.
All it does is move your camera
Oh ok
You would still access the camera's Transform the same way
also btw both arent being called at the same time ive just kept them in one script so i dont have to send 2
You would need to explain what components are on the object and also how the object that is doing the holding is moving/rotating
I'm assuming there's probably a Rigidbody involved here?
If that's the case then moving it directly via its Transform is the main issue here.
the rigid body is set to kinematic when its being held
This worked @wintry quarry
so how should i move the object then?
via the RIgidbody, with interpolation enabled, in FixedUpdate
e.g. rb.MovePosition
you shouldnt get input in fixedupdate, it will make inputs feel laggy
yeah the KeyDown in FixedUpdate is also an issue but that's separate
GetKey is generally acceptable
Yeah I forgot, thanks
Why do you have to multiply stuff by time.deltatime?
bcuse peoples pc's can drastic wildy.. my update() loop may run at 300 fps when urs runs at 100
if ur doing calculations.. those need to be scaled to happen at equal rates
When you have a number like "points per second" you need to know how many seconds have passed so you know how many points to give.
deltaTime is exactly that - how many seconds have passed
(since the previous frame)
Δ
in other words, if you want to increase health by 1, every 1 second, if you were to write health += 1; then 60 frames later (assuming stable 60fps), then you will now have 60 health.
whereas time.deltatime is a very small value, so 1 * time.deltatime produces a value that is small enough that, after 60 frames, you will have gained the correct amount of health
Anyone have a video on how to make a simple changing HUD. I need to make so there is a display of the current player speed and position (jumping, standing, crouching etc.)?
did you search Youtube, there are dozens..
you can edit the text property of a text component in code
to whatever value you want
reference the script with the stats, display it on the ui
Thank you both
Dll Not Found Exception!!
I am learning Macos/iOS plugin development in Unity.
plug-in is inside: Assets/Plugins/TestPlugin.bundle
There are two cases
1: Checking in Vmware Macos (intel CPU)
Everything is working fine; there are no errors
2. Testing in real Mac with (Slicon CPU)
We are getting the Dll not found exception.
We even tested with other older plugins and self-made plugins
But none of them are working on a Mac with a silicon CPU.
Only the plugins that are regularly updated by their developers are working.
We are probably missing some settings while building the plugin in Xcode.
Could you please help solve this issue?
Plugin:
https://github.com/gamedev1991/OS-X-Plugin-For-Unity
uh shouldn't those be System.IO
idk
why UnityEngine.Windows?
I have a player movement script and I was wondering if I can get some feed back.
https://paste.ofcode.org/gv77Kx9LA8L86MqqTnmk75
oh well then switch to System.IO
The UnityEngine.Windows.File class is available only for the Universal Windows Platform. It was recommended during the times in which the System.IO.File class was not available for the Universal Windows Platform. Now, the System.IO.File class is available for the Universal Windows Platform, and Unity recommends not using the UnityEngine.Windows.File class anymore, but the System.IO.File class instead.
https://docs.unity3d.com/ScriptReference/Windows.File.html
interesting..
Just wanted to know if its good/need any changes
oh
- eliminte magic numbers
- can simplify some stuff by using ternary operator
- you have exposed
rbto the inspector but it will get overriden in Awake, making it pointless being exposed - your function naming conventions is not consequent (
isOnGroundis lowercase) and it's indicating that it will return abooltype because of theisprefix, while it's just a void (bad naming i'd say)
just by quickly glancing over it
should the names of the custom functions all be lower case?
No
how should I name them then?
By following the c# standard naming conventions you can Google it up
should it be IsOnGround?
void Update(){
var grounded = IsGrounded();
HandleDrag(grounded);
}
private bool IsGrounded(){
return Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, ground);
}
void HandleDrag(bool grounded){
rb.drag = grounded ? groundDrag : 0;
}```
just read it through and that was very useful I will make sure to stick to it
alt version edited :p
just to clarify do I do the same things to these aswell?
those are fine as private variables should be camelCase. Generally people prefix _ with private but thats mainly preference now days
I prefer not
alright thanks
This sound file should be a clean loopable tone, but when I imported it, it inserted silence on both sides, any way to fix or fix on reimport?
Figured it out, I needed to convert to a WAV
[Serializable]
public class LootTable
{
public List<GameObject> loots;
public int tableChance = 50;
}
[CreateAssetMenu(fileName = "LootTable", menuName = "Scriptable Objects/Loot/Table")]
public class LootTableSO : ScriptableObject
{
public List<LootTable> table;
}
everytime i open the project the script object keep saying this cant be loaded
i think this script object has serialize issue? but no idea what to do.
yea, you can also go in and change the compression mode in import settings
sometimes works.. sometimes not.. but yea stick to wav format.. Unity doesn't process it as hard-core
What did you click on to get to this window?
Is it a GameObject, an asset, or what?
the script object from the lootableSO
Do you have any compile errors?
no, no red
Try putting only the ScriptableObject class in the file, and move the other one to a different file
when i create it its fine, when i restart unity it lost
And make sure the file name of the script matches the SO's class name
alright i got a bit of a weird question, is there a way i can make something look at another thing, but have constraints, so like it cant go over -90f, to 90f on a certain axis. Ive tried to do this myself before but itd either not rotate at all, or just move once then stop
myVal = Mathf.Clamp(myVal, min, max) transform.rotation = quaterion.euler(myVal, y, z) etc.
and is there a way to make this occur in a function
theres just one problem, i think i tried that and for some reason it didnt wanna work, what type of "LookAt" am i using, LookAt() or the other one which i forgot how to do
oh the look part, uhh use LookRotation
well you can apply the limits after look at too i think
restart unity still lose it :(
You've moved the other classes out of it as well?
yo, i did it but when i am swinging its just sitting at 90? i ran into this issue so many times and idk whats the problem???
yes this is the entire script
i did get told that saying min : -90 and Max: 90 is just gonna return 90 but idk how that works
Hm... can you show a screenshot of your console? Including the settings for it at the top of the window?
Vector3 direction = target.position - transform.position;
Quaternion targetRotation = Quaternion.LookRotation(direction);
Vector3 eulerRotation = targetRotation.eulerAngles;
if (eulerRotation.z > 180) eulerRotation.z -= 360;
eulerRotation.z = Mathf.Clamp(eulerRotation.z, minZRotation, maxZRotation);
transform.rotation = Quaternion.Euler(eulerRotation);```
Some like this maybe
Well, if something's at -90 degrees, it's also at 270 degrees, which is higher than 90
And there's really no way to know which number that represents the same angle it's going to give you
the settings of the console? i dont think i understand
this is the warning for random material
Okay, just wanted to make sure errors weren't hidden.
Do you have a .meta file for both the ScriptableObject script and the instance of it you created from the context menu? They won't show up in unity, you'll need to check in the file system for them
nope, dont work. infact theres no clamping at all lol
in game atlease
how would i represent this?
in code
yes both exist a week ago
still exist
https://discussions.unity.com/t/clamping-angle-between-two-values/782349
There's a helper function in the first answer of this thread that shows how you can convert an angle into values between -180 to 180, then you can clamp it
i add a random comment of just //
and reload script, and it back to normal
Do you have any sort of version control on this project? Is it in a folder affected by OneDrive or one of those other malware Windows Productivity Tools
Git wouldn't be affecting things unless you actively run git commands, so that wouldn't be it.
uhm how can i make it elastic ? it worked with linear but once i made tElastic it displaces it by 1.5-4 (based on duration which is random??? shouldnt be tho?)
private class Move
{
public Vector3 direction; // The movement offset
public float elapsedTime;
public float duration;
public bool IsComplete => elapsedTime >= duration;
public Move(Vector3 moveOffset, float time)
{
direction = moveOffset;
elapsedTime = 0f;
duration = Mathf.Max(0.01f, time);
}
}
private float EaseInElastic(float t)
{
float c4 = (2 * Mathf.PI) / 3;
return t == 0
? 0
: t == 1
? 1
: -Mathf.Pow(2, 10 * t - 10) * Mathf.Sin((t * 10 - 10.75f) * c4);
}
private List<Move> activeMove = new List<Move>();
private void Update()
{
if (activeMove.Count > 0)
{
Vector3 totalMovement = Vector3.zero;
List<Move> completedMotions = new List<Move>();
foreach (var motion in activeMove)
{
motion.elapsedTime += Time.deltaTime;
float t = Mathf.Clamp01(motion.elapsedTime / motion.duration);
float easedT = EaseInElastic(t);
totalMovement += motion.direction * easedT;
if (motion.IsComplete)
completedMotions.Add(motion);
}
transform.position += totalMovement;
foreach (var motion in completedMotions)
activeMove.Remove(motion);
}
}
public void MoveObject(Vector3 offset, float duration)
{
activeMove.Add(new Move(offset, duration));
}
Unsure then, that was my last idea. If it's not OneDrive or some weird SVN thing I dunno what would cause it
dang
i put debug logs and both t and easedT reach 1 at the end
ok i got the looking at working, but whenever i clamp the angles it just dont wanna work
ima try clamping from 0 to 90 to see if its me or the code buggin
nope, its the code, clamping dont work a tall
if you free can you help me create one of this script object
i wanted to see if my unity broke then
here the script if you can help me
[Serializable]
public class LootTable
{
public List<GameObject> loots;
public int tableChance = 50;
}
[CreateAssetMenu(fileName = "LootTable", menuName = "Scriptable Objects/Loot/Table")]
public class LootTableSO : ScriptableObject
{
public List<LootTable> table;
}
I'm on a phone, can't run it
ok nw
have you set up much related to this script? if the file name matches, and you have no compile errors, then it most likely is just a meta file issue. If this object isnt used much, you could delete the meta file and unity will recreate it
maybe check your version control to see if the meta file ever changed in a weird way
yea thats seem to fix it
the old instance lose the script but still manage to hold the data
Did you rename the class and file name in your IDE before? that is one possible cause for why the meta file might've messed up
not that i rember
renaming in ide itself then i can say i never done it, i always try change file in unity project window
hm well its hard to speculate what couldve happened, but the advice i was gonna say if you did the above would be move/rename things inside unity to avoid this stuff. I had a similar issue once before and it was a pain in the ass to find what was wrong because the console gave the most vague error
and if the code was used in many places 🤷♂️ !
for now idk, if it works it work hapy boy
and thanks for the simple solution
trying to run this code and it's giving me these errors
configure your !ide, these errors should show in 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
then afterwards, i would split that line up so you can see it more clearly. the errors are quite clear in what they're telling you, but you have everything in 1 statement so its hard to understand which type is which. Plus also that error about how you're using GetComponent is clear if you look at an example from the docs
Plus also that error about how you're using GetComponent is clear if you look at an example from the docs
yeah that was a silly one
Hi guys! Hope everyone is well! I was wondering if there is any online documentation or perhaps a manual about most c# fuctions with the unity system. I am very knew to coding and the way i have been learning languages like java and processing is thru code and then reading it, and having a manual to search and read what what does is of great help!
Thank youuu
good evening
im trying to control a boolean property in my shader, and for some reaosn it's gone kaput
you should double check the methods on the Material class 😉
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Material.html
and for some reason, this does exist
... do I just se tthe boolean property's value to 1 and 0 and call it a day?
yes. and for future reference, don't trust shitty AI to provide information to you
in light of recent development
how does one get the shader material to work?
cause this is what its supposed to look like
and its just gone
Hey everyone, quick question.
I’m creating a 2d desktop game and the main functionality is based on a square grid and involves planting crops/farming simulator.
My question is:
is it bad practice to use only UI elements for the entire interactive game? Or should I use sprites and use the world coordinate system?
The entire game can be played only by using mouse clicks and drags. Very minimal.
is it bad practice to use only UI elements for the entire interactive game
Yes very bad practice
Ok that’s what I thought. Thank you. 🙏🏼
The shader needs to be compatible with a sprite renderer.
If it's your own shader, start from fixing the warning on the sprite renderer.
_MainTex != _MainText
But I assume you noticed that.
also older shadergraph need you to set the props to global not sure with the newer unity version
on the properties
Is https://learn.unity.com/pathways a great place to start if my goal is to make 2d games & im new to coding
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
like in inspector or
working?
not sure, usually i am using ASE
let me check my shader code first
how about activate the override prop declaration
while the exposed is turned off
Yes
Alright thankyou
override prop declaration?
wait what unity version are you on
below the Exposed
2022.3.57f1
try this
are you on URP or BIRP?
urp
ok turn out name and reference should be correct, doubt that it actually do anything and there's some false positif from unity
I want the camera not to exceed the map created at runtime
I tried using cinemachine confiner3d and the idea is to read the size of the map and increase the size of the cameraconfiner to limit the camera
I searched online but still couldn't find a better way
can someone help me
You'll need to get a reference to the module and modify it's fields:
https://docs.unity3d.com/Packages/com.unity.cinemachine@2.1/api/Cinemachine.CinemachineConfiner.html
is this unlit or 2d shadergraph?
sprite unlit right?
wth i thought you said you use URP
i thought i did too?
use alpha clip, but srpite should be rendered using transparent surface type
well this tosses a wrench in the plans
and it need stencil support as well for spiret and UI shader
where?
okay yay!
@sand mesa for fututre reference, this is a code channel, your issue was not a code issue
Okay so I'm not crazy 😄 I thought I was in #archived-shaders this whole time lol
does unity not have the init keyword? I see some posts that say if you include
namespace System.Runtime.CompilerServices
{
class IsExternalInit
{
}
}
people say it should work but {init;} is still erroring for me
init keyword? Never heard of it in C# context. Or any other languages I'm dealing with
Compiler services?
Aah, I see. It's something from C# 9 it seems.
I don't think unity supports it yet
Besides, the init keyword seems to be related to properties, not classes.
If that's not what you mean, then maybe provide some context to your question.
no it is, its for properties in a class yes
its just more useful for some variables instead of making either 100 different constructors or a construct with a bunch of defaults.
im surprised that it isn't implemented yet. Its a fairly old feature
Unity is pretty far behind in terms of C# language features. This is because it's still using Mono. Work is under way to upgrade to .net
Is there a way to make my button, after it is clicked & deactivated, return to its original color when i bring it back?
It changes color on hover
It should transition to default state when disabled.🤔
At least according to 2018 docs.
on what version?
- But it's unlikely to have changed since then. Canvas button, right?
hey yall, quick question about design patterns -
my lecturer mentioned that it's worth looking into dependency injection (inversion of control) for Unity, but the more I look into it, i start seeing that it's unnecessary as Unity either already uses some form of DI, or that it's just not needed
asked my project teammate as well and she seems to have the same observations
Is it actually worth it to implement some form of dependency injection for unity?
Strictly speaking all design patterns are unnecessary because you can always do the same thing with any design pattern or without one. It's just a matter of how structured you want the project to be. It becomes more important the more developers work on the same codebase and when it uses automated testing. Some people like to use DI with Unity, most don't, especially solo devs.
hmm ok i see, thanks!
Did they provide any specific examples? Passing components through inspector is basically already DI but when people say DI that usually refers to existing libraries. It's usually those libraries that are concerned overkill
Yeah that's why i was thinking if implementing DI is even something worth considering, as passing through inspector basically does that already
He didn't provide any examples though, just said to look into it
It could even just mean calling a method to provide references to your components. You could definitely try a framework once but a lot of opinions I've seen is that it's not really needed. In game dev, I'm always cautious of advice that's related to "decoupling" because at the end of the day your code is pretty much going to be tightly related and cant function without each other. That's just how games work
Alrighty thanks 🙏
!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/, https://scriptbin.xyz/
📃 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.
This is my CursorManager class. I basically do hide and show cursor here. In my first playable scene I call hide cursor in Awake. The cursor starts hidden but as soon as I move my mouse. It unhides itself somehow. I thought it would go away in the build but it happents there as well. What should I do? I have to press escape to get my pause menu and then close it back to hide the cursor again.
A tool for sharing your source code with the world!
did you search other scripts for the Cursor class
You might have multiple copies in the scene, so one hides it and the other shows it. Try putting logs in HideCursor and ShowCursor, disabling collapse in your console if it's enabled, and seeing the order those functions are getting called in
I did log. Its all hiding cursor. I have been having this issue ever since I started working on this game. I also searched other classes that may be unhiding my cursor too.
It starts hidden until I move my mouse to look around.
I even tried calling HideCursor 2 times both in awake and in start.
I am considering doing it in update only for once too.
did you search every script in your project?
Yes
I solved it by calling hide cursor in the update as long as the game is not paused.
bandaid onto a bigger gash
I dont know what else to do though.
People saying its a bug in the internet.
May be related with my unity version i think
how searched all the scripts
In vs code. I searched for HideCursor and ShowCursor
oof
I did say search for the Cursor class
I also did that too
Searched if i was calling it thats not under my CursorManager class. Like manually
Nothing shows up.
in vsc did you select the entire folder
show
dont do it manually
Here
you looked through all 358 results?
also would probably narrow it to Cursor.visible = true
no. The others are just third party stuff that I'm not using.
the third party stuff can affect your cursor too though
I only know I'm showing cursor on Dialogue start. Thats all
how do you know one of those scripts isn't in the scene on a gameobject somehwere?
you have 8 files with this Cursor = true so how do you know for sure
Put a breakpoint on each of those, then run the game through the debugger
I bet is whatever charcontroller you are using
Ill do it
None of the Cursor.Visible = true lines except the one i call it in CursorManager Class meets the breakpoints
Btw I'd also just search for just Cursor.visible =
Because Cursor.visible = someBoolOrCondition is a thing
Also are you using some kind of character controller or camera package?
I plan on having a script, MorseTranslator, that holds some functions for transcribing text into both written transcripts and audible sound for morse code for my game project
The functions will be used in a few places, and my plan is to make a monobehavior script, and just attach it to every other script that ends up needing it
is there a better way I haven't heard of?
Camera package is just cinemachine. Not sure if you're asking about that. Character controller is just using legacy inputs. I think I followed a youtube tutorial for it when I first started working on the game.
is there a reason you need it as a monobehaviour instead of just a plain c# class? if you make it a monobehaviour, that'd imply you are actually serializing data or using it to attach functionality to your object
The reason being when I was learning, I learned monobehavior was the default and was never taught why the different types exist or their use cases
im not sure what logic you're gonna use it for, but it sounds like those "transcribing text" methods could even be static. meaning it isnt associated with an instance of the script, it exists with the Type. This is assuming you dont need it to function differently for different objects also.
you use monobehaviour if you want to attach the script to a game object. it doesnt sound like you need the logic on the actual game objects.
which is why you learn c# first ;p
I signed up for C#, arrived at class, and it was a unity class
the name of the class in the college coursebook was "C# programming" and I feel at least mildly failed by them but I do have an additction to game creation now
teachers having their license from cereal boxes now?
i do find it shocking how often people in here talk about doing a course about unity, and the code provided to them is an abomination
I'm going to be giving the player a signifigant amount of information, communication, and dialogue through a telegraph, so my game's scripts for dialogue are going to pass through this and be given to the player as beeps, light flashes, or ink scratches depending on difficulty and accessibility settings so I need functions to take text, and output a string that can be taken by any translation object, so Beeper, FlashBulb, ScratchLine, and EasyModeTextBox
Most likely going to use doubles to store the morse, with 0 for dot, 1 for dash, 2 for space between letters and 3 for space between words
it's almost always a paid course too, usually from udemy
my PHP teacher used to be an AWACS operator for the Navy, and he once started a sentence "This is a non-comprehensive list" with the intonation implying that a noncomprehensive list was a thing to learn about, and not "This is a non comprehensive list.... of functions that work with this thing"
local technical college
double is overkill , a simple byte can work no?
i dont know why you'd need a double for that, id probably use an enum which you should learn.
if you've used the legacy input system, there are methods like Input.Get... which are static methods. in those cases you dont attach a class to your game object (though the new input system works differently). you can just access the methods from anywhere
its just odd to teach a c# class but jump straight into unity, without at least introducing the basics types like a POCO and such.. but eeek php is C language family, makes sense ig
It'll be one variable holding the entire transmission, something like
Hello please send medicine
would become
.... . .-.. .-.. --- / .--. .-.. . .- ... . / ... . -. -.. / -- . -.. .. -.-. .. -. .
would become
111131312113121132224 -etc
yea dont use a double for that. use a list for each number, like a list of enum
oh you wanted to store the whole thing ? thought like an array or something
This looks like a valid code for a human to consume, but it's actually not very good for computers to deal with.
and then Flash bulb will turn
111131
flash 30ms (x4)
pause 30ms (x1) etc
yeah a list makes sense, I hadn't put much thought into that part yet
Working on the morse to plaintext stuff first, hadn't thought about the abstract layer yet
best to keep ur cursor logic in a single place.. easier to deal with.. if the cursor state changes.. i know exactly who did it
enum would also be good
honestly im not sure why you even need to translate
.... . .-.. .-.. --- / .--. .-.. . .- ... . / ... . -. -.. / -- . -.. .. -.-. .. -. . into 111131312113121132224
its not like you would display the numbers to the user
Your flash bulb should have some code which directly takes that first string, reads . and knows it should do flash.
you have the string anyways. mapping . to flash is the same as mapping 1 to flash
yeah that makes sense, I might change to that
I know it's more efficient to send numbers than strings but that's overkill for something of this scope
not even overkill thing, its also easier for you to process specific things to a function or asset
i wouldnt care about performance here. and the .-/ stuff doesnt need to be a string either. it could still be that list of enums
you're going to iterate over it anyways
the difference would be your flash bulb would do.. (pseudocode)
if myString[i] == '.'
flash
compared to
if myCodeList[i] == CodeEnum.SomeValue
flash
its a more defined way rather than using magic strings in every object that needs to translate the code into action
Do you prefer visual studio or visual studio code for programming unity?
I use VS for Unity, VSCode for Web
i use whichever one i see first
im not really sure what im looking at here. your enum would literally just define the different morse code characters and thats all.
then you have a list of enum
public enum MorseSymbol
{
Dot, // Represents a short beep or signal
Dash, // Represents a long beep or signal
LetterSpace, // Space between letters within a word
WordSpace // Space between words
}```
ya was also thinking something like that
public enum MorseCode { Dot, Dash, } //etc..
void Method(List<MorseCode> code){
foreach (MorseCode codeItem in code){
ProcessMorseCode(codeItem);
}
}
void ProcessMorseCode(MorseCode code){
switch (code){
case MorseCode.Dot:
//etc
break;
case MorseCode.Dash:
//etc
break;
}
}```
*oHHhhhhh * I see what you mean now
I thought you were saying to store the message itself as an Enum for passing between the archive of dialogue crap and the output boxes
the only thing still missing then is I need a function to let me write dialogue in ASCII and the code translated it to morse for me, I know how to write the function itself but I'm not sure where that script should live, because it'll need to be accessed and send information to multiple objects
oops added that to my project 😄 , i dont need morse code in my project
How do I get the Intellisense to finish the string or see the two options with the keyboard? sorry for the crappy question
Tab?
up and down arrows
tab and up/down arrow keys
that could likely be a static function as i mentioned, just in a plain c# class
How could i check if the player stops walking?
controller.velocity.magnitude
what if they're side strafing?
idk
If i do arrow keys it brings me on the other options below not on the preview I don't know if you understood me. It brings me on name, tag, #if, etc...
if you want to check when the player has stopped pressing movement, check that all the inputs are false
If you want to check if they've stopped moving, like if ice levels are a thing, check velocity
you are missing () after the if
Yeah I'm new sorry lmao, I'm just taking time to how to navigate on IDE
@shadow rain
you can also do for efficency. But Velocity mag is fine
var sqMag = controller.velocity.sqrMagnitude
if ( sqMag <= minDetectedIsStopped * minDetectedIsStopped)
etc
Thank you
And instead here if I press tab it doesn't put the <> symbols
getcomponent be finnicky sometimes
sometimes u just need to help it along the way
make sure to assign it to something tho...
GetComponent<> by itself doesn't do anything
MasterMouse theMouseThing;
theMouseThing = gameObject.GetComponent<MasterMouse>();```
Ah that's why I was looking for a way to make the “major” and “minor” symbols due to the fact that I'm using an American keyboard on Italian layout (spaghetti) and I can't make the symbols... I might as well use the American layout
I encountered this issue again before. And tried to fix it before making the CursorManager class. Thats why the mess 😦
ahh yea. i mean thats a solid solution..
just gotta clean up the mess thats left over lol
https://scriptbin.xyz/ewujukiwul.cs heres mine.. its a Singleton pattern so I can call it anywhere i wish..
Use Scriptbin to share your code with others quickly and easily.
MasterMouse.Instance.HideCursor();
i had soooo many problems like ur describing
tyy
where third party assets would take my cursor over
and all that crap
had to go in and find each and every script that tried to do it.. and jot down which ones should really control it
so my gamemanager was that puzzle piece... only the gamemanager can lock /hide/ confine the cursor.. and to do that it has to tell the MasterMouse (my cursormanager) to do it
Yeah its a mess for me. Trying to find whats causing it.
wait how could i check if the player is even moving
My game takes around like 15-20 minutes to complete. So I figured forcing it in update would be okay.
Didn't you already get an answer for this
i thought i only needed when to check if the player stops moving but i actully need the opposite
Same thing but you invert the condition
Instead of velocity.magnitude < you'd use velocity.magnitude. >
Or just read your inputs directly
if cc.velocity.magnitude < reallySmallValue or.... ☝️
depends on ur controller.. mine is apparently finnicky.. my magnitude kinda bobs there at the end. b/c i have momentum coded in..
in my case i'd want to check the inputs instead
If this is about animations then using the input is probably the best so the player gets instant feedback when they start/stop moving
yea ^ i like snappy
Yes, as long as you have set up the animator side properly
You can also do something like animator.SetFloat("Speed", velocity.magnitude)
alr
If you don't just want 0 or 1
//velocity method
if(characterController.velocity.magnitude > 0)
{
//we must be moving
isMoving = true;
}
else
{
//we aint
isMoving = false;
}
//input method
if(verticalInput <= 0 && horizontalInput <= 0)
{
//we aint moving
isMoving = false;
}
else
{
//we are (or rather, should be)
isMoving = true;
}
what do u mean?
this would be easier with linking a float and using the blend tree
is it ok that
Hey guys a quick question. Is there anything that I need to pay attention when I am importing assets such as veichles or maps that were made originaly in unity 20xx for example and I am using unity 60xx?
oh she'll let u know
it just goes straight to the walking animation
well that means the condition tied from idle to walking was triggered
or there simply isnt one
haha alright thanks
just check the console immediately after import
if no errors.. u should be gucci
i cant see why it would matter..
its not like fbx formats have changed
now if they have scripts attached yes
Ok ok, just need a few simple vehicles and a map to test it on
you'lll probably need to refactor
lots of functions have been deprecated since then..
if u run into any of those its easy enough to google to find the alternative method
or ur IDE will tell u
Ty
umm.. thats the same condition is not?
if a number is greater than 0.. it can also be less than 1
every number from 0 - 1 in fact
no but it just goes straight to the walking anim
ya, b/c the condition that sends it to idle.. is also true to send it to walking
it should go to idle from entry w/o a condition..
the only conditions should go from idle to walk and then walk to idle...
idle to walk would be if > 0 and from walk to idle would be if < really small number
try that ^
if > small number.. if less than small number
i use booleans.. so im not 100 percent sure
a Blend-tree would be hella useful like Nav mentioned a while back
do u use Raw inputs or smoothed inputs?
b/c if its smoothing.. thats probably causing the issue..
b/c it slowly ramps up from 0 - 1
idk
if var > 0.1f -> walking
that it or am i thick?
if var < 0.05 -> idle
if u make a little deadzone it shouldnt re-trigger the walk instantly
if speed > 0.1
to what u js said
what abt the other one
if (speed > 0.1f) // Prevents instant re-triggering
animator.SetBool("IsWalking", true);
else if (speed < 0.05f) // Ensures it fully settles before switching back
animator.SetBool("IsWalking", false);```
this is how i usually do it.. i control the bool in code.. and just use bool as transitions
idk my brain is starting to hurt lol
alr thats prolly easier tbh
the simplest thing would to be to go off ur inputs
if 0 if 1.. only two states it could ever be in
unless ur using Input.GetAxis <- b/c this one has smoothing
Input.GetAxisRaw does not..
its either -1, 0 or 1
The problem was that both transition conditions were true at the same time because every number between 0 and 1 satisfies both conditions.
ya that should work
now just use that (1) bool for ur transitions
fun fact: theres always a dozen ways to do a single thing..
disclaimer: my thing may not be the best thing
😅 lol
else says it needs a ;
it is
got it
that should be underlined red
show full, works fine here
good catch!
just goes straight to walking
yeah no worries
have you tried debug logging the value of speed
no.
this is a case where i should just use properties right?
well you should always "record" the actual values in console so you verify whats going on behind the scenes
like a public get private set
especially when ur debugging/problem solving
hell yea
Do you need to set them?
i mean via the script
not externally no
not sure why i did it this way.. i think its b/c i didnt want to expose the private variables
but i still needed to be able to read them elsewhere from time to time
i just noticed how ugly and offputting it looks
or maybe thats just me lol
only difference I would still use Is prefixed to the bool so I know for a fact its boolean, but thats preferences
wait a minute!
whats teh difference between public bool Grounded() => characterController.isGrounded; and public bool Grounded => characterController.isGrounded;
weren't you reading from magnitude or did I miss something ?
negative
they use speed
ones a method and ones a property
ok right
they do the same thing tho right?
so what now
technically now they are since its a 1 liner
thats correct
have u debugged the values again?
dont think so
yea.. speed needs to = velocity.magnitude
read the magnitude or set the proper speed thresholds
I have decided to scrap the camera look script and use cinemachine and to my surprise IT FIXED THE STUTTERING YAY! My question is how can I make the movement relative to the camera? so which ever direction I am looking at I can move that way.
dam I been said yesterday to use Cinemachine lul
Guys from experience most of the assets on unity store are for built-in render pipelines? Is there a way to tell because I imported one and everythings pink and I have URP
Yep I should have listened lmao
Just wanted to know how I can make movement relative to the camera?
oh you're nt rotating bdy anymore?
matching the camera you would need to pass the forward to the rb moverotation then
I'm going to do that in the player movement script as well I just wanted to do the movement relative to the camera first
its kinda backwards thats why I was confused on that
So I started learning Scenes and here I am checking if there is a next scene or not. I think I did it right, I just don't know how to get the length of the scenes.
find the materials, select them and convert them
should tht be my variable or whatever @rocky canyon
could I use this from the camera look script to rotate the rigidbody/player?
i imagine most assets use BIRP as theres no real reason not to (unless its specifically for HDRP), plus it makes the asset more accessible as not every developer will be using URP
you would just need the forward from it
but keep it locked to Y only
@analog drift under the edit menu, this is what you want to click
But how do I check if the current scene I am in is bigger then all the scenes count??
GetActiveScene / GetBuildIndex
Yeah I found it and it works, thanks. For future reference is there a way to do everything one time or do I need to find every material and do it one-by-one?