#💻┃code-beginner
1 messages · Page 200 of 1
It's "based on recent edits"
Did you remove any other null checks recently?
i actually added them, copy pasted from other script
Otherwise, yeah, makes no sense
Hah, super weird
I guess this question fits code-beginner best:
I struggle getting intellisense working in VS Code, am I missing something obvious or should I just switch over to Visual Studio?
There's the VS Code extensions (Unity, C# Dev kit and C#), then there's the Unity packages (Visual Studio editor, and according to some guides Visual Studio Code editor, but other guides say I shouldn't have that even though it's got VS Code in its name).
!vscode
Visual Studio Code editor
This extension is old and no longer a part of the install, and you should remove it if it's present
If you haven't restarted after configuring that may fix it
I've done all the steps mentionedi n that article, set VS Code as the external editor, and also regenerated the project files. Several times.
Which one do I have to restart? Unity? VS Code? Both?
Your computer
Computer
wait what
Or log out and back in, either one
I got it working, once, without having done that
the website you linked to didn't mention having to do that either
It is a well known thing that can fix it
Do it or don't, your choice
Doesn't seem like a big deal to me
When certain things install they want to modify the PATH, which requires logging out
if the thing wasn't already configured
sure, but usually you get the "do you want to restart your computer now or later" prompt in those cases
https://unity.huh.how/ide-configuration/visual-studio-code
I have some various troubleshooting steps here. VS Code is definitely more finicky than VS Community, but it's much better than it was previously
And also more lightweight and takes way less disk space
Until you add the extensions to add the missing features
Thanks a lot for the tips and the links, I'll look into this and try to figure it out
Vs code is literally just vs with stuff removed
If I wanted all the missing features, I'd use Visual Studio. I chose VS Code because it's more lightweight
The debugger is an important one
True, that's a pain
Ooh, this could also have been part of it:
I just open the script files, not the project, and that could cause all sorts of issues
To be fair, modifications to PATH are immediate. It's just that running apps and services retrieve them once when launched.
That's generally totally fine if it's working already 😛
But then again, I did get it to work sometimes
So in most cases it's enough to restart the program that relies on the path variables.
Unless they rely on some kind of service or background process that doesn't close with the app.
I considered having to restart Unity Hub...
You are spawning them every frame
In Update() you don't have any check to stop it from spawning in the next frame
Update runs every frame
Not only do you spawn them every frame, you increase level every frame, which makes you spawn a BIGGER AMOUNT
Start runs once in the objects lifetime
well this isn't true, they only increase the level if the asteroidCount is zero
I didn't see asteroid count go up anywhere
Start runs once in the objects lifetime
Which... seems like it's what you want
the Asteroid ups the count in Start()
Typically, you would check a condition every frame and if it's true you execute some logic.
That applies to any feature you might want to implement.
Oh dang, didn't even see the second script till now
On mobile
Actually
I think you can just move the rest of the code in update into your if(asteroidCount == 0) check
yeah
when you run out of asteroids, it ups the level, and spawns the new ones
otherwise, the spawning code doesnt run
are there asteroids in your scene intially?
Is AsteroidCount changed in the inspector?
It will take precedence over the initializer
having external addition of your asteroidCount makes the code more confusing honestly
Is there a reason you don't just up the counter when you spawn the asteroids?
ah ok
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To 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.
Probably means plane
so pass that axis in the new vector3
You're passing a z of zero into ViewportToWorldPoint
You construct a Vector3 with only x and y, so z defaults to 0 afaik
And the z is the distance from the camera in this case
So 0 distance from the camera is probably not what you want
new Vector3(x, y, z)
See what you are missing there in all those edge if statements?
Yes
You have new Vector3(x, y)
Yeah, it depends on where you want it
You could pass in the players distance from the camera
It seems like that's what you'd like?
Or maybe the camera near clip plane? And then they fly "out" to the player
Always?
Hmmm, I may he wrong... because this is an absolute position.
And 0 should put it at the player then...
I need to look up the docs for ViewportToWorldSpace
Ok ok, yeah, z is distance from camera
So you want it to be +13
-13 would be behind the camera
I think
I think this code looks like it expects an orthogonal camera view?
Is this from ChatGPT or something?
Ok yeah, it's expecting orthogonal
Since that's what makes 2d 2d for the most part
I am not sure. You could try setting viewportPosition.z to zero..
I dunno though sorry
with Random.OnUnitSphere is there any way to increase the radius in which it randomly chooses a location
Multiply your result by a scalar
Guys, I remember not using the old UI of the Editor, but suddenly it changed to this older UI. I'm using Editor 2022.3.15f1
Is there new ui? 🙂 Am I missing something?
no
This is the current UI
I think it's a bug or smt
it's your layout, not "different UI"
also as i said, this is a code related channel
That's not different ui, it's different layout
I know
The color is a bit different, that's why I ask about it
then don't post non-code related questions here
Top-right, Layout. Color is the same imo
what is the easiest networking system for begginers
At least tell me where can I ask about this?
easiest is not doing networking as a beginner. You wont have fun
all networking solutions have their pros and cons. None are easy
okay then what is the easiest to just make a test prototype
rigidbody -> constraints
im using screen wrap, everytime they wrap the screen, they drift 1 unit forward on the z axis
im not sure how to fix it
idk then i just started unity
without seeing the code, no one can really help
void Update()
{
//doing this allows for the screen to wrap with no regards to screen aspect ratio
Vector3 viewportPosition = Camera.main.WorldToViewportPoint(transform.position);
//need the ship to wrap on the opposite side it came from
Vector3 moveAdjustment = Vector3.zero;
if (viewportPosition.x < 0)
{
moveAdjustment.z = 0;
moveAdjustment.x += 1;
}
// need to have the opposite, so if you go the other way, then you will wrap around as well, this prevents you from always spawning on the same side
else if (viewportPosition.x > 1)
{
moveAdjustment.x -= 1;
}
//this is essentialy the same as left and right screens, except swap out X for Y since you are working with the top and bottom screen.
else if (viewportPosition.y < 0)
{
moveAdjustment.z = 0;
moveAdjustment.y += 1;
}
else if (viewportPosition.y >1)
{
moveAdjustment.z = 0;
moveAdjustment.y -= 1;
}
//the reason for doing this method of screen wraping, is to cover for the possibility of hitting two screens at once, such as a corner.
transform.position = Camera.main.ViewportToWorldPoint(viewportPosition + moveAdjustment);
if (viewportPosition.z < 0)
{
moveAdjustment.z = 0;
}
else if (viewportPosition.z > 0)
{
moveAdjustment.z = 0;
}
}
here is my code for the screen wrap, im not sure how to make it to where when they wrap on teh edge of the screen, they stay on 0 = z
ok but you do moveAdjustment.z
after you change the position aswell
if (viewportPosition.z < 0)
{
moveAdjustment.z = 0;
}
else if (viewportPosition.z > 0)
{
moveAdjustment.z = 0;
}
these lines could be removed and nothing will change
they dont do anything
ok
whats the next step
i accidently just deleted my script folder not paying attention
did i just lose everything
revert it on git
🤷
people divide into 2 groups:
- those who make backup
- those who will be making backup
try CTRL+Z in the file explorer
Try looking in the recycle bin.
yeah i did
i found them thank god
but im still stuck on my issue, i have no idea where to look to find a solution
well fix the bigger issue at hand, that you arent using version control
you just had a scare of losing an entire folder
right i just made a backup of my project in case on github
and saved a copy of the project on my pc
as for your issue, try doing some basic debugging as to why the z value is moving. like log the viewportPosition and moveAdjustment
as i said already
you are modyfing the z
after setting the position
that if/else could be deleted and nothing will change
it's doing nothing right now
noone asked you to delete it
you dont understand what i am saying
read what i wrote
read your code again
you are modying the transform.position
THEN AFTER THAT
you are changing the moveAdjustment.z
it has no effect at all
you are changing moveAdjustment value on Z axis to 0
but then you are doing nothing with it
yup
well it requires just some logic thinking
set the Z value BEFORE assigning the transform.position
i cant change the size of this in battle canvas
this is a code related channel man
yea isnt it a code fix
do you have any code to share?
arent u meant to put some script in
no
that's what google says
don't ask non-code related question in code related channel
you cannot change size of the canvas
unless it's world canvas
read again what i wrote
your moveAdjustment.z = 0 does NOTHING
because you are not USING IT
anywhere
it's just an empty value
Why are you even helping
yea im done at this point 😄
This person needs to learn basic c#
tried my best
Please read the pinned messages for tutorials on using c# @fiery notch
Sometimes that's all we can do 🥹
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
PlayerInput playerInput;
private void Awake()
{
playerInput = new PlayerInput();
playerInput.Fatlad.Move.started += context => {Debug.Log(context.ReadValue<Vector2>());};
}
}
``` Im wondering why this is not recognising Fatlad
Sometimes you need a mental refresh.
What fat lad?🤔
PlayerInput.Fatlad
Oh, where do you have it defined?
Take a screenshot
You're adding events on script, I haven't tried nor think of that NGL.
The only assumption I have is that the action map aren't set up properly.
Is the action map compiled into a C# class?🤔
Didn't have the chance to work with it yet.
yes
Im following a tutorial from iheartgamedev
It’s a basic character controller
I would do that but this guy is using completely different things
And I won’t know what to do
If I don’t follow
Share the tutorial and timestamp
Unity offered three methods of doing it from the editor.
I want to learn how to make a character controller and then a hierarchical state machine what recourse would you guys use
Two of those are shit.
1 is very shit. 
I can't point out rn since I'm not in computer.
because its not inside the if? @fiery notch
you only set isAlive to true when you collide with the asteroid
@static cedar somebody pls help 😭
and you do the rest for all other colliders
I learned from CodeMonkey's tutorial.
CodeMonkey did a hierarchical state machine
Huhhhh
I learned... The new input system specifically.
Why you ping someone while saying "somebody"?
Real.
Everyone knows. It's not hard.
Yes?
J-bear is learning it rn I think.
By my own bad advice, I think you can help each other for that matter.
Or think wether you need it in the first place...
I think it's a nice way to organise different character states. 
I'd say it's handy.
It depends on the context, but I wouldn't never use it for a character controller
how would you recommend I learn it
At most, I'd use a simplified version, where I just have a current state enum and update based on it in the character controller
Start from learning a normal state machine. If you get it right, implementing a hierarchical one would be easy.
An enums and a switch case is a valid state machine I think.
very incorrect
They are. What I mean is that you don't need an elaborate system where each state is a separate class.
switch and enum based state machine might work for small state machines
but imagine when you have a state machine with like 20-25 states
and a big switch for that
So it's valid, but for a small scale.
C++, but still
ok so what
it doesn't mean its proper approach
just because some AAA level games have that lol
Point is, it's working.
sure, didni't say it doesnt
And it's also matching the state machine definition.
yup, didin't say it doesnt aswell
So what is incorrect then?
Well I didn't quite say that. 
"a proper approach" is a really subjective thing when it comes to code architecture
Well, you're not moving except on z axis to the value zero.
Is this 2D or 3D?
No clue why this isn't working.
!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
• Other/None
What does it do instead? (Continue to go up or down without constraint?)
Try logging the y value before adjustment and after adjustment
Or the entire vector..
I'm referring to your code.
it's kinda hopeless helping him, we've been trying to help him since 2 hours now, he's lacking very basic c# knowledge
just fyi
Ahh..
a quick question. I'm using the 2023 build of unity. But visual studio was last updated in 2022
Well, my advice is to log the view port position before and after adjustment. It would tell you what you've changed that wasn't appropriate other than setting z to zero - which likely isn't the sole issue.
That's fine.
Players won't run on your game in Visual Studio for starters.
It's just that i'm still having the same issues.
Your IDE version and Unity version do not have to match. It's merely a coincidence that they're using date-year as the version indication.
I see.
I havn't signed in for instance but i doubt that's the problem.
it is not
i thought autocompletion
Also, consider removing that else in front of the if statement for checking the y bounds of the view port position.
It is part of that.
IDE not configured*
it is working
he's writing code in it 😉
You are using "myRidgidbody.velocity" but you created a Rigidbody called "rigidbody2D"
the more important issue is, that his IDE is not configured
otherwise he would have that error higlighited
hence why i told him to configure his ide
I do understand that, I was just pointing out the error also.
I don't know how to change it's name.
Don't help users with a misconfigured IDE, please
You would edit either one so they both match just like you would correct an error in any text file using Word
Alright, but the guide set by the server suggests not giving answers if an ide is unconfigured.
If they are unable to figure out how to change text in the IDE how do you expect them to configure the IDE? I am trying to help them get to that point. Either they are VERY new to computers or a troll. I think we can help them get to the point of configuring the IDE.
Not sure why you'd argue about a simple rule, configuring it is not hard
Having a misconfigured IDE is a bigger issue than whatever they are trying to solve
5 minutes of work at most
And if they are a troll then it's easy enough to figure out
Maybe for us. Like I said they just stated they don't know how to change the name of a variable. Obviously they are too new to do the basics yet.
It's literally 5 minutes of work when you use VS and only 4 steps with multiple pictures
It literally cannot be made simpler than this
Also I haven't seen any posts about issues during configuration so idk why we're assuming there is one
if they are having issues following a STEP BY STEP guide how to configure ide
then don't learn how to code
Well renaming a variable is very simple too. Even simpler actually. I suspect there could be a language barrier
But hey maybe we can ask @tender mirage how the configuration is going instead of bickering about the steps
so idk what are you talking about
I think following the guides is for the best of the community. The server has got a feedback channel for suggestions but other than that, folks often take it to DMs if they're willing to provide syntax support due to lack of intellisense - I think the guide was really well thought out for the best of the community and the game developer.
he'll just come with mose issues and errors
without his IDE configured
think about it and follow the #📖┃code-of-conduct
Why are you guys arguing
What's the point of it
One mistake wont do much
Anybody knows what this keyboard means?
what am i supposed to google
Idk
I'm unsure if it's a keyboard even
Have you tried hovering over it to see if there's a tooltip?
That was going to be my question lol
It's for unity shortcuts somehow
Playmode strikes again
Well, it's definitely not a coding question. Consider asking #💻┃unity-talk
Sure, I just thought it would impact the code
How so?
if you havent coded anything related to it, then its likely not a coding issue
Well, Fair point. I'm not here to start an argument for it
hey im trying to implement a movement mechanic for a game using unity's "new" input system and following this guide: https://www.youtube.com/watch?v=ZSP3bFaZm-o
Currently the player can move, but only once when I press the corresponding input key that I set up. I tried playing around with the FixedUpdate() and Im assuming FixedUpdate has something to do with the continious movement I want rather than once per press but not sure how to use it. Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.Windows;
public class playerController : MonoBehaviour
{
[SerializeField] public float walkSpeed;
[SerializeField] public float dashSpeed;
[SerializeField] public Vector2 moveVelocity;
private PlayerControls playerControls;
private Rigidbody2D rb;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
playerControls = new PlayerControls();
}
private void FixedUpdate()
{
}
private void OnMove(InputValue input)
{
rb.velocity = input.Get<Vector2>() * walkSpeed;
}
}
In this video, I cover everything regarding Unity's New Input System. I walk you through how to actually implement this system as well. It is a bit longer of a video, but it is the most thorough out of all the videos I have seen as well. I started out not knowing how to even use it, to know only using this to control my game. Hope you all enjoy ...
feel free to tag me if you know, ty!
Does it immediately halt or simply slow to a stop over time due to friction?
it moves when key is pressed and slows down to a stop
so the OnMove() is triggering, but only when I press the key not hold it, and I want it to continiously move while im holding it which is where the FixedUpdate() comes from
and I tried changing the interaction in the input system with HOLD but the result is the same, only with a slight delay between the movement and the key press, but that makes sense, as i need to hold it for the OnMove() to trigger in the first place
i also tried adding to the FixedUpdate() rb.velocity = moveVelocity so that the rb.velocity changes in fixedupdate to the rb.velocity (and changing moveVelocity inside the OnMove() based off the input to rb.velocity ) but that didnt work either
basically I just wanna understand how OnMove() can continue to execute while holding down the key rather than just once
New input system, right?
yep
Usually the idea is you only check when you press and when you unpress the button.
as continuous readback is not usually what you try to do
so does that have something to do with ctx.performed, started, canceled ?
cuz currently Im using send messages NOT invoke unity events
It's not like you're giving input of different speeds every frame, so the only thing you care about is when it started, and when you decide to let go of that button.
whats the simplest way to reference the gameObject of a scripts child
assign it in the inspector
so i need to change my script to fit with Invoke Unity Events rather than send messages? Then use the OnMove() to change the velocity based off either ctx.performed ?
why doesn't gameObject. child work
because that's not what that is for.
If you want to get the component via code, then use GetComponentInChildren<T>() for a single component, or GetComponentsInChildren<T>() if there are multiple of the same component.
I've only used it with unity events and the callback context, so I've not too sure how it would work with send message.
Send messages.. the thing that uses strings? Never use that
Literally ancient techology.
Is there a way to attach a
private GameObject gameObject; with private TextMeshProUGUI textMeshPro; in a class Example ?
Or is TextMeshProUGUI itself a game object?
TextMeshProUGUI is a Component
It's attached TO a gameobject, but I'm not exactly sure what the question is.
how would I change the script to work with unity events tho? Ive only used send messages, so not sure how to use the callbackcontext, and I didnt quite understand with the documentation
This one if you're new.
#archived-code-general if you have a few months of experience
#archived-code-advanced if you're lost in the sauce
not sure what to put in ctx
Could you guide me how I could get that private GameObject named gameObject to have the component textMeshPro get attached to it? I am just so confused
thanks!
GameObject canvas = GameObject.Find("Canvas");
gameObject.transform.SetParent(canvas.transform);
doesnt work // gameObject = gameObject.AddComponent<textMeshPro>();
textMeshPro.text = count.ToString();
textMeshPro.rectTransform.localPosition = new Vector3(50, 0, 0);
}```
doesnt work // gameObject = gameObject.AddComponent<textMeshPro>(); this doesn't work
textmeshpro isn't what you want
TextMeshProUGUI would be the component you want to add.
Better to use TMP_Text
ya?
Yep, easier to type, remember and it's the base class for TextMeshProUGUI and the 3d one, so can be used for both
AddComponent also returns T provided, you may not be able to set "gameObject" equal to that directly
but that's not my question i wanna know how to add the textmeshprougui component to the game object i created
in the same class
oh
I think I understand the confusion though. They probably don't understand how generics work.
actually, adding the component, you wouldn't use TMP_Text
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.0/manual/Actions.html
ReadValue<Vector2>();
The docs does say it could be easier just to poll the input, which makes sense for analog stuff.
Do
TextMeshProUGUI textMeshPro = gameObject.AddComponent<TextMeshProUGUI>();
This adds a TextMeshProUGUI component to the gameobject, and then returns a reference to it, which will be stored in the textMeshPro variable for you to manipulate.
this is the full class I actually want to reference the textMeshPro in the class not create a new variable of TextMeshProUGUI in the constructor
let me try that
with the rectTransform you want to set the anchoredPosition not the localPosition
should i reuse as many variables as I can by making them public to other scripts
like the mouses position for example
No
alright then just do textMeshPro = gameObject.AddComponent<TextMeshProUGUI>();
I didn't see you already had a variable with that name defined.
nope
ok that actually worked, although now my player moves very slowly when starting the game and moving... im assuming I can just mess with the gravity and moveSpeed to see how this interacts with each other ?
Your default for pretty much everything should be private.
encapsulation, code tidiness, code readability
you should never have public fields (variables)
^ also mouse position can always be accessed from Input.mousePosition no?
There's some variable like that
Anyway, a big part of keeping your code clean and maintainable is defining how it interacts with other code. Just making everything public can lead to you being unable to track exactly how a value is being changed.
did that but some errors that ill look into but just wanted to clarify
A Game Object is bigger than a component right?
Like components are attached to the Game object not vice versa, right? so why am I making my textMeshPro equal to gameObject.addcomponent
@rare basin public fields are bad and shouldn't ever be used, there's no need and can lead to spaghetti code, poor maintainability etc
Also [SerializeField] is just for debugging and stuff since it makes it easy, mhm?
GameObjects have many components attached to them. Each component knows which GameObject it's attached to.
It causes private variables to be exposed in the Inspector.
So more like "initializing".
no, it's not for debugging
I fucking wish it was for debugging. Why doesn't unity have some ReadOnly attribute I can slap onto things? Maybe I want to see something without beng able to affect it.
you mean... readonly ?
So like shipping a game with [SerializeField] is a thing?
No like, see it in the Inspector, but it's greyed out, so I can't modify it.
can't everything be done with code and private?
yes, of course. It exposes a private field to the inspector
naughty attributes has a readonly attribute, but otherwise you can make yourself one in a few lines of code
You must be able to do it.. Unity components do this
You can't access a private variable from another class
I know they do, but its not in the engine as a built in attribute.
unless it's inner class
Like Mao said there's resources to get behaviour like that.
Just odd it isn't in the engine baseline.
There is a small editor script you can setup that basically toggles GUI, as a custom attribute, but its odd its not just built-in to the engine as an attribute already, like MultiLine or TextArea etc are
unity expects other devs to pick up their slack or stick to custom editor scripts
no reason not to have* an easy way to hide and show property fields serialized values
Yes but I doubt any beginner in here is going to use nested methods 🙃
They probably just haven't thought about it as well
I doubt I will use them aswell lol 😄
I've used a nested method maybe once or twice in the 5+ years I've been coding.
the highlighted line gives error object reference not set to an instance of an object
What I want to achieve is the numberSpawner class creating a gameObject that is child of canvas in the hierarchy
Anonymous methods, ya tones.
But just another method explicitly written out within a method?
then canvas is null
Odd shit.
canvas is Null, because using GameObejct.Find(string) is bad and prone to errors
you shouldn't use any Find() type methods tbh
so changing it to invoke unity events and adding the context param in my move(), worked. However, now im trying to implement a jump mechanic and this isnt working and im not sure why
what should i use
Is it? That gameObject variable isn't set anywhere.
FindObjectOfType<T>() is fine, as long as it's used wisely
sure for some manager or singleton
gameObject doesn't need setting, it's a standard property that ALL MB's have
No but like... in this script, where is the variable gameObject set?
it's a property from MonoBehavioru class
oh, I see.. they've declared their own var called gameObject .. that's null
Tell me that one more time.
It's fine-ish. We're not in a Monobehaviour class anyway.
then what is the purpose of gameObject
you don't set it anywhere
also change the name of that variable
how do i do physics-based spinning on a mesh collider
as this is misleading and it's a unity reserved name
I just wanted the gameObject to be the one that has a textMeshProUGUI component attached to it and then i wanted to use that gameObject elsewhere
a class having an attribute of gameObject is a bad idea i reckon?
Is NumberSpawner not a monobehaviour on purpose?
that's a field (class level variable), not an attribute
Attribute means something else. A regular class having a variable of type GameObject called gameObject is fine.
Kinda the big question here, ya.
it is fine, yet confusing, for sure you can make a better name
Whats the goal here
i forgor why i even removed it now 💀 so bad
guess just testing if it works without monobehavior?
if what works
it needs to be an MB to be in the scene
because i have another script attached to canvas known as "GameHandler" which is monobehavior
I saw that Mr. Wash.
accidental click on that emoji ;p
so what
that doesn't mean NumberSpawner cannot be MB
doesn't mean it needs to be
didin't say that
It's also fine to use plain classes like this, but you need to make sure you set the MB stuff you use
but will need to pass in a gameobject to NumberSpawner
If you're just testing how code interacts, that's all good.
Learning and messing arond is part of the process.
yeah just fing around and finding out im not doing anything big
just trying to make smth where i click and a number spawns and goes to 100 and then gets destroyed
it did work before when i had a gameObject created inside the constructor but then i was like what if i make a gameObject in the class itself
but then i got errors n got confused
private void OnCollisionStay(Collision collision)
{
if (collision.gameObject.CompareTag("Player"))
{
transform.eulerAngles += (Vector3.up * timeSpent) * Time.deltaTime;
timeSpent += Time.deltaTime;
}
}
private void OnCollisionExit(Collision collision)
{
if (collision.gameObject.CompareTag("Player"))
{
timeSpent = 0;
}
}
will this code stay the same between refresh-rates
It's important to remember that variables are sort of just "boxes" for things. They need to be filled with the right thing if you want to do operations with them.
If they're empty, then their value is "null".
Which is why you get those "null reference" exceptions.
Or object reference exceptions.
So when you wrote the underlined line, you basically just created an empty box that can hold a GameObject.
And then tried to do things with an empty box.
In code I'm changing the colour of a material for UI re-skin purposes (material.color = newColour;) and most UI elements are changing their colours accordingly - but some aren't. I've checked that they're using the Material, and also can see that the Material object in the Project window is updating to the new colour.. Is there something that forces a UI element to refresh its material?
ahhh that makes sense
what value is jump force
okk... then its not working how I want it to. The player is not moving up when I hit the button
100
the value is 100 currently
also, moveVelocity will set your Y value to whatever that is, overriding your jump.. probably..
thats what i wanted to say
I see. I added that because the current Move function only applies once without adding that in the FixedUpdate. It only moves once when I press it, but when I hold it, it still only counts as a press and moves once
im not sure what u mean by "in the inspector". Do I add a debug.log after the addforce in jump with "rb.velocity" ?
no, enable debug mode
in the inspector
you can see velocity in there
not sure if you even need debug mode
under nifo there is velocity
this is the debug log i got when I added it to the jump method. In the rigidbody info inspector thing, the Y velocity changes quickly ( i cant see the value cuz its too fast) then drops back down to 0
WHAT THE HEELL
wasn't private GameObject _gameObject; isn't _gameObject supposed to be an object of GameObject?? and isn't it supposed to be used after it has been defined in the class
gosh i feel so stupid this was the reason i wasted 4 hours
this gives no errors now
why are you doing = new GameObject();
that will create a new, empty game object
is that what you want?
nvm
my bad
so in an example class if I define "private GameObject _gameObject"
It will be an empty GameObject associated with that class
how come even renaming it give null exception
What makes it show up in hierarchy?
Entirely unrelated
oh
is it fine to split up things which could be in one script into multiple if it helps read better, or should I use a script to it's fullest
Something will appear in the Inspector as a slot if it's serializable
split up
[SerializeField] GameObject _gameObject?
how can I get the component of a child while naming what child I want to get the component of
so how would I change it to go up cuz this isnt working either
remove * before jumpForce?
not saying it will work, it will at least compile 😄
sry typo, still not working. it says velocity cant be changed cuz its not a variable
can't find it from searching
your trying to get the velocity of a rigidbody but velocity is from the transform component
read the link vertx sent you
You can GetComponentsInChildren to get all similar components, but you need a way to identify which one you want to use. If possible, just set this reference in editor time using serialized fields.
like I dont understand why addforce isnt making it jump when pressing the input i have
You're overriding the velocity every FixedUpdate
i did just use serializedfields but i thought thered be a way to specify the child you want to get the component from
well, GetComponent will be the way without a direct reference
well I added that because the Move function only moved once when pressed, even if I held it. I had to repeatedly press it in order for the player to move
it's better to not rely on the names of gameobjects for your game logic to work, so if you can hook up a direct reference that's preferred
you can use transform.Find, but why would you do that garbage when you can just serialize a reference
@north kiln
idk memory or something
but if that interferes with the jump, im not sure how to fix both
how are you getting velocity from a rigidbody
mb im stupid
Personally I wouldn't be writing a player controller from scratch without a tutorial unless you're familiar with how to interleave this stuff properly
there are so many tutorials, example controllers, etc, etc
well i was trying to use this: https://www.youtube.com/watch?v=ZSP3bFaZm-o
In this video, I cover everything regarding Unity's New Input System. I walk you through how to actually implement this system as well. It is a bit longer of a video, but it is the most thorough out of all the videos I have seen as well. I started out not knowing how to even use it, to know only using this to control my game. Hope you all enjoy ...
which went pretty in depth
I have two sprites which rotate towards the mouses position, but how can I stretch it to the point where it reaches the mouse
the pivot isn't centralised
but with the same code, it worked, but im assuming the creator didnt mention it only moved once. They didnt talk about fixed update or anything. I also have been searching a few tutorials but some of then get too confusing when I try implementing other mechanics I want for my game
so im trying to go slowly implementing each mechanic making sure I understand what is exactly happening
You're just doing it wrong
so yea, removing the continious resetting of the velocity in fixedUpdate allows me to jump, but without it, my move() doesnt work continiously. I would have to keep pressing it instead of just holding it
The video ends with him being able to jump and move, and hasn't used any Updates
Re-do the video and watch closelierly to see what you missed/ did differently
well I dont want to copy his exact script, im just trying to understand the new input system in its entirety. Ive watched it more than a few times, but now im stuck cuz from what Im understanding, this should work, but its not, im stuck, and thats why im asking here for help
You don't understand it
{
public NumberSpawner()
{
Debug.Log("Called Constructor!");
}
}```
```public class GameHandler : MonoBehaviour
{
private NumberSpawner numberSpawner;
}
the debug.log isn't showing, the constructor isn't called?
Do the tutorial exactly as is, AND THEN mess with it and try to mix it up
I have but his tutorial doesnt specify the issue with the holding the input button for move() to continiously move
i have to repeatedly press it, and he doesnt address this issue I have
because there isn't an issue to work around
You've done something differently to him.
i know, and the difference is im trying to get the move() to work with holding as opposed to continiously pressing the input button. And I dont want that, I want to be able to just hold, where as his just does move() when pressing it
with this channel, I was able to fix that with adding something to the fixedUpdate(), but now my jump mechanic doesnt work
I know what you want. You have implemented something different to him.. if you know what this difference is, go change to the same as him
Updates shouldn't really be used with the new input system, they're not needed
well the fixedUpdate() change worked for me. And the unity docs mentioned fixedupdate should be used when working with physics based movement, which I am. If I shouldnt use updates, what should I use ?
Show a screenshot of your entire player actions window... make sure to select one of the movement keys
the 2d vector
I do poll in update for some mouse stuff using the event system, but I think it's because there's some conflictions with the IDrag interfaces or something. I forget.
sry
are A and D set to hold?
basically the jump mechanic works if I dont use fixedUpdate() for movement (my fixedUpdate() continiously resets the velocity)
if I dont use fixedUpdate(), the move only works once per press, not holding the input key. (idk why addforce isnt working tbh)
If I can get one, I cant get the other. Ive tried multiple interactions (hold, press), but they are not doing it either
so I doubt its the inputActions, its the logic, but I cant see what it is
then copy the tutorial and it'll become probably obvious ¯_(ツ)_/¯
its not becoming obvious. Like I said, ive watched it multiple times, followed it exactly once and works just like his does, but his movement is not what I want atm. I started from scratch to just start at a ground level so I can get the mechanic I want, but this is what Im trying to fix now
I have created a Bullet system
Using RigidBody and a Sphere and set Bullet speed to 65
Any think I can improve this code
using UnityEngine;
public class Bullet : MonoBehaviour
{
Rigidbody rb;
[SerializeField] float bulletSpeed;
private void Start()
{
rb = GetComponent<Rigidbody>();
rb.velocity = transform.forward * bulletSpeed;
}
void OnCollisionEnter(Collision collision)
{
Destroy(gameObject);
if (collision != null && collision.gameObject != null)
{
if (collision.gameObject.CompareTag("Enemy"))
{
Debug.Log("Enemy!");
Rigidbody enemyRigidbody = collision.rigidbody;
if (enemyRigidbody != null)
{
enemyRigidbody.AddForce(transform.forward * 500);
}
}
}
}
}```
A skybox material is added to the light settings for the scene
also, what's the code question here?
So ,I should add the skybox component in directional light rather than on camera?
Band_L.localScale.z = lengthToBand_L;
What could be wrong? Band_L is a transform and lengthToBand_L is a float which takes a magnitude
Directional light != light settings. Anyway, this is a code channel. Delete your question from here and ask in #💻┃unity-talk
you cannot change the components of transform.localScale directly
First 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
• Other/None
then fix the underlined errors
I updated it but it's still there.
If your IDE is configured the errors will be underlined in red
and you will have proper code autocomplete
read the guide posted above
There are many more steps than just "update"
its not just about the version but how its configured
i keep getting spammed [Collab] Collab service is deprecated and has been replaced with PlasticSCM how do i stop this
#archived-code-general message and please don't cross-post
Follow the link and read what I posted
ok i fixed it
so im trynna make a game where when the player destroys an obstacle, they're supposed to get the buff corresponding to it (the buff will be displayed on the obstacle)
How do I go about implementing this considering I have spawner(s) in place which constantly generate obstacles at random time instances (like how do I have each obstacle generated assigned a buff to it and how do I randomise say multiple buffs for each obstacle spawned)
Make a list of possible buffs in the spawn manager, give each obstacle a field that will store the buff, then on instantiation, set the value of that field to a random buff in the list
if PlayerScript playerscript;
then why do we have to playerscript = GetComponent<PlayerScript>(); as well when playerscript is already PlayerScript?
Defining a reference doesn't magically assign it. Which PlayerScript would it refer to if it did? Would it just guess?
ite imma try this rq
yeah that makes sense!
PlayerScript playerscript; that line only defines the name of a field and what type you are aloud to store in it. not what you are storing in it
What does that mean.
!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
• Other/None
You need to set up visual studio correctly to work with unity
just follow the guide
Follow the steps for whatever code editor you’re setting up
you are asking if the confugartion of your IDE is completed
then you are showing unity console screenshot
Can you show a screenshot of Visual Studio
Nice job, seems configured to me
A babies first step indeed.
Something I’ve been wondering about c# is why functions aren’t auto declared async. I mean, they’re the same thing up until you say await, so…
very incorrect
C#/VB/F# compiler playground.
Aren’t async functions synchronous until you write await?
Remove the word async and compare the two lowered pieces of code
even if it was the same code, i like that it enforces in the signature if its aloud to await or not
and makes it hard for someone to accidnelty add one to a function that is not called in a way where that would be a good idea
but also the generated il is totally different
It would definitely have mixed messages in a codebase, with usage being very unclear
btw I also looked this up and one thing came across a lot called "ScriptableObjects", considering I've only just started like almost a week total in experience could someone break down what those exactly are (and how they may help my cause if they do)
Hmmm still seems to not like being ran.
did you add it to a object
did you save it
is the GameObject active?
and assign the rigidbdy to it
Did you assign the rigidbody?
does it have a Rigidbody?
I’m a little confused. I thought async methods functioned synchronously until it reaches an await keyword. So why can’t each declared methods just be async, and if they use await, then they work like an async function, and if they don’t, they act like a synchronous function, which they already do?
What are use cases for "internal" ?
You didn’t assign the value of Myrigidbody
the a in async stands for Asynchronously
You really need to go to Unity Learn to learn the basics
Sorry, I’ve never used those, maybe someone else can help you though
you prolly need to drag your birdie in unity into the empty field of rigidbody iirc
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
That's what i'm doing
mostly for making libraries, its kinda like public but can only be accessed in the currently assembly and not thigns that reference it
to really use internal, you need to be able to make assemblies
and it is pointless to describe the use cases until you know how assemblies work
Yeah, but aren’t they synchronous until they reach the await keyword? So if there isn’t an await keyword in the method, then it’s just a normal, synchronous function, right?
like i have a npc behaviour editor i made, as its own assembly that uses it heavily, so it does not need to expose implementation details to the user of it
Also I think you're getting this from Game Maker's Toolkit's flappy bird tutorial so I'd say try going through each thing slowly coz he kinda really zooms through stuff (it was where I started too just see each thing thoroughly)
As for the error its prolly jus the drag n drop thing i mentioned within the Unity console
imagine you have a package, that is one assembly. Internal lets all scripts in the package use it as though it is public, but blocks anything from outside the package from using it
I might've skipped some steps because my bird got deleted
yea go through it thorougly its like 40 mins but give it as much time as possible coz it really is all basics you'll need at your fingertips for when you start yolo-ing stuff
you know how you can define a class, and make instances of it?
ye
scriptable objects are a type of class where the instance is written into a file
you can make .asset files for that scriptable object; and it functions as an instance that you can reference
its like a way to make your own custom asset file types
the main use case is for immutable data. Like if you have a class to hold parameters for guns/enemies/characters, that should be an SO (scriptable object)
i see
SOs behave weirdly with instantiation. so 2 rules of thumb:
- Avoid instantiating SOs during runtime. You want to use CreateAssetMenu in editor.
- Avoid modifying the values in an SO at runtime.
I gotcha
there are ways around this, but if you break these rules of thumb, you will struggle. especially if you don’t 100% know what you are doing
What weird behaviour do SO's have with instantiation?
ite I'll try reading into SOs beforehand so i dont mess up my stuff and decide whether to do it safe or go with this
almost all fields in my SOs are defined like this:
[field:SerializeField] public int myValue {get; private set;}
what does SO mean
nothign really just gives you in memory coppies, keep in mind only serlized stuff gets coppied in it, so other fields revert to defualt values
GC does not automatically remove them.
ScriptableObject . . .
also you need to explicitly call destroy like its a GO
isnt that every object...
no
you mean properties, not fields, right?
ScriptableObject is a class
did oyu mean GameObject?
yeah, I define auto-properties with auto-backing fields, is the more correct way to say
regular old C# objects you never need to destroy explicty the GC system does it after it goes out of scope
nope, a ScriptableObject is an asset stored in your project folder. it's a Unity Object . . .
and in build, every time you open the application, SOs are effectively reset to whatever was there when the application was built
this is very different from editor mode, where modifying an SO in play mode of editor can permanently write to SOs
i did it YESS
this is why you should avoid modifying SOs at runtime
right now, all my SOs have all properties/fields with only private setters. NO public setters
i made that mistake once of having a public field in an SO, and I paid for it dearly
you can do it depends on usecase, so got a node editor that does stuff as runtime, and the nodes are SO's, but when it does runtime stuff with it it creates in memory instances from the assets
how do i make fishnet work with different devices, it is only working for windows on my computer
They have a discord
GetComponent<Rigidbody>().AddTorque(GetComponent<Rigidbody>().angularVelocity * 5, ForceMode.Force);
im trying to make the rotation force of a rigidbody exponentially increase. i tried using this, but it does nothing. what do i do?
If it is 0, multiplying it with 5 wont do anything
also please cache the Rigidbody to a field
both for code readablity and not having multiple get components per frame go off
cache that Rigidbody, please . . .
all of this GetComponent<Rigidbody>().AddTorque(GetComponent<Rigidbody>().angularVelocity * 5, ForceMode.Force);
could just be
_rb.AddTorque(_rb.angularVelocity * 5, ForceMode.Force);
but yeah like mentioned if starting for still, 0 * 5 is still zero
you can even remove the ForceMode since Force is the default . . .
why are you writing 3 dots at the end of every sentence
it’s his thing
alr
unless I make it mine…
you made it wrong . . .
well at first it was "...", but then i received ". . ." for leveling up. i'm not sure if they're is anything afterwards. depends if i can keep climbing the ladder . . .
Maybe someday you can get as high leveled as me ⚪ ⚪ ⚪
The highly saught after fourth dot . . . .
🙌 🙇♂️
i should make a game about finding the fourth dot. smth like, "RandomUnityInvader() and the Great Dot," oh wait, that sounds familiar . . .
the real deal is adding your signature after every discord message
- mao
i like it . . .
but it is spinning
What is making it spin?
the player
jumping into it
its a roundabouut
Have you confirmed that the code is running? Because it should go crazy pretty fast
Check your rigidbody's angularDrag too
It will slow down rotation
yeah im watching it, and it is definitely changing
but its not, going crazy fast
angular drag, not angular velocity
oh angular drag
Idk then, maybe some other code is modifying its rotation or angular velocity
it has a hinge joint. does that affect it?
Most likely
the point is its a roundabout on a playground, that should go stupidly fast
the code is running, i checked with a debug.log
Show the settings for the hinge joint?
That looks ok. I think the angular velocity just gets way too large and the physics system limits it
Or it's just spinning so insanely fast that it looks like it's spinning slow
I just tested with code similiar to yours and it reaches maximum (0, 150, 0) angular velocity
It looks like it is spinning slow but it really isn't
The sources I am following say using strings in any means is bad practice because it wont throw an error. How do I check the tags if im not to use strings for example. other.tag == "Player". Whats the better version of this?
CompareTag()
CompareTag is better, but doesn’t actually fix the core issue where the argument is a string
compare tag is asking for string no?
The package I linked autogenerates static classes with public const strings that you can use to compare string and layer names
Ah okay I'll check it out thanks.
so instead of gameObject.CompareTag(“Player”);
it would be
gameObject.CompareTag(Tags.PLAYER);
yes, the difference is CompareTag will throw an exception with an invalid tag, == string will just silently fail
Ahh makes sense. Thanks for the answers.
== and CompareTag become equivalent with the Tags class because the Tags class cannot contain constants that are invalid tags
I tried this but there seems to be no such thing as Tags.
Tags only exists with that package
the package contains a source generator to automatically create a file for a class called Tags
and same for Layers
2023 also has an option to use "TagHandles":
https://docs.unity3d.com/2023.3/Documentation/ScriptReference/Component.CompareTag.html
See second overload
It isnt bad or anything if i get used to using it right?
anyone knows why reloading scripts takes such a long time? didnt use to be that way for me but now 1:30 to 2:00 is what it takes and thats just wild
to using this package?
yes
Thanks.
the worst you’d do is update the Tags class yourself
in a scenario where you have been using it, and then the package gets nuked
Okay thanks all for your time. Also, Happy valentines day!!
which only requires small effort when new Tags/Layers are defined
how do you run commands in the console
what unity calls the console is really just a log viewer
for just executing some code in the editor when you want most people make a menu item for it
https://docs.unity3d.com/ScriptReference/MenuItem.html
in the tutorial im watching he has this console menu thing in the game view
would have to see it to know what, but chances are that is something added
❤ Watch my FREE Complete Multiplayer Course https://www.youtube.com/watch?v=7glCsF9fv3s
✅ Learn more about Relay and UGS https://on.unity.com/3tQZLLW
📝 Relay Docs https://on.unity.com/3OjXL8z
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
👇 Click on Show More
🎮 Ge...
also doesnt show how to get the ui
its not spinning slowly. i know with certainty because im reading the angular velocity, touching it, etc etc
i tried using a motor to set the speed to be super high and it worked, so it isn't reaching a limit
I didn't say it was spinning slowly
well, its not spinning fast but appearing to be slow
its definitively very slow
different issue. this is a script to return a vector3 (ying). if it doesn't hit anything, it will just set ying to the end of the raycast, but if it does it should set to the point it hits.
if (Physics.Raycast(pivotTran.position, pivotTran.position + pivotTran.TransformDirection(0, 0, -1), out hit, 8, layerMask))
{
ying = hit.point;
}
else
{
ying = pivotTran.position + pivotTran.TransformDirection(0, 0, -8);
}
it only seems to set ying to the end of the raycast, regardless of whether or not it hits. im unsure what to do
Debug.Log to see if the hit is ever actually happening
Is it possible to pass a normal array as an argument so that the receiving function can only read the array elements? Like is there some keyword I can prefix it with so that the array is readonly in that given context, but not others?
btw pivotTran.TransformDirection(0, 0, -1) is excessive - you can just use -pivotTrans.forward)
oh yeah lmao
You could pass the parameter as an ICollection<Type> instead of an array
Or IEnumerable
it depends if you need random access or just iteration
adding debug.logs for some reason, fixed it?
i literally just added debug.logs and it suddely works what on earth
I've seen that happen a few times. This usually means that...
- you hadn't recompiled
- you have something random / execution-order dependent
or, option 3:
- your debug statement changed the meaning of the rest of the code
Sorry, I had it slightly wrong. It wouldn't be passed as a parameter. But maybe it doesn't matter.
private byte[] buffer = new byte[4]; // should be modifiable elsewhere
public byte[] getBuffer() // whoever calls this should not be able to modify any elements
{
return buffer;
}
ok so to put it into some context (might not be absolutely right but just the idea i got from reading this and online)
SOs are basically a separate abstract class that basically hold all the base values/parameters (like in my case the player stats, obstacle hitpoints and stats, projectile stats etc should all be an SO)
These values are not to be messed with directly during runtime within the SO, however I should be able to call em someplace else and edit/add onto them (say buffs/debuffs) in that specific called instance and after runtime is over, the base stats are remain unchanged/reset as a separate and safe entity
(Please correct if im not wrong just trynna make some basic layman context/sense here)
return as readonly collection as mentioned
i mean, if i had to guess its the second one
private byte[] buffer = new byte[4]; // should be modifiable elsewhere
public IReadonlyCollection<byte> getBuffer() // whoever calls this should not be able to modify any elements
{
return Array.AsReadOnly(buffer);
}```
because i've saved and reloaded many times
i've had this issue for about a week and i only realised now i should change it
Thank you, thank you
now i just need to figure out why this:
rb.AddTorque(rb.angularVelocity, ForceMode.Force);
isn't doing anything
It doesn't make any sense
why are you using angularVelocity as a parameter to AddTorque?
Also if the angular velocity is currently 0 then there will be 0 torque
this is similar to rb.AddForce(rb.velocity) which also doesn't make sense
because its moving
@wintry quarry its spinning
but i want it to spin even more
also about this, the 2nd line is just to like initiate the SO class, however for context in the first one, fileName = asset im creating, menuName = SO (prolly just what general term its coming under), and order = order of execution of SOs right????
exponentially so
Well are you calling it just once
or in FixedUpdate for example
no, im calling it every frame
oncollisionstay
then it should work
but depending on the moment of inertia
but its not really speeding up at all
that might be very small torque
well it is moving
log the angular velocity each frame
i know because im slamming the player into it
also your angular drag might be overwhelming the tiny torque
zero
it’s worth mentioning that constant torque means velocity changes linearly
all i want is for the thing to speed up its spinning when the player touches it
if torque is proportional to angular velocity, then angular velocity will change quadratically, which is probably not what you want
how do i inherit a collider from its parent for a child script
your question makes no sense
basically
you can’t inherit colliders
good to know
what are you trying to achieve?
basically a locked door system
if you touch the object and you have a key to unlock it, it destroys the instance
what does any of this have to do with inheritting colliders
i thought i could put all the scripting in the form of a child object
basically i slot the child into an already existing object
The script that does OnCollisionEnter or OnTriggerEnter needs to either be on the object with the Collider OR on a parent object with the Rigidbody
generally interactions between objects works best with scripts on the root objects of interacting entities
putting scripts on child objects tends to add complication when they need to interact with the rest of the world
this is true, up to the caveat: as long as it is easy to tell them appart as much as you need
if the child object is just an extension of the parent, to help organize hitboxes etc, then you probably do not want a script
but if the child collider has the same layer collision properties, and unique logic for just itself that let it be managed like a truly separate thing, then it should have a script
eg my players and enemies all have a little trigger hitbox inside them to know if they are being squished by solids. This hitbox usually has its own script, as the behaviour is generic, regardless of what it is on
[CreateAssetMenu(fileName = "HP", menuName = "ScriptableObjects/SpawnManagerScriptableObject", order = 1)]
public class SpawnManagerScriptableObject : ScriptableObject
{
public float hp;
public float maxhp;
public float minhp;
}```
@buoyant knot this is basically how to make a SO for hitpoints right? (sorry for excessive pings just wanna get this over with)
Now I can just call this SO elsewhere whenever I need the HP values (say under Player and/or Obstacles)
For a locked door I would tend to have a setup like this:
Door - (Door script, Rigidbody)
- Door visuals (Collider, Renderer)
in the OnCollisionEnter I'd basically do collision.collider.GetComponentInParent<Door>() then interact with the Door if it exists
i'd remove hp as that is a mutable value which the object should track itself . . .
yeah, but a few points:
- you don’t need to put scriptable object in the name of your class. it should probably be called EntityStats or something.
- So not make them public. Use:
[field:SerializeField] public int maxHp {get; private set; }
i see
yes. Remember we don’t want to store mutable things on an SO
imagine a single .asset file being like the definition of the parameters that make up a Pikachu
and a different .asset for Shellder
the values in the .asset should NOT change during runtime
i see a lot of people use config and data for SO naming, like: EntityConfig, EntityData . . .
gotchu
I call one EntityData, because that is an SO that is very generic, on anything that is an actor in the game
i also have separate EnemyMovementData, to store parameters specific to enemy movement
No errors in making the SO so far, gonna try implementing this into the game and will be back if any other error
because not every entity has movement behaviour
just remember:
[field:SerializeField] public int maxHp {get; private set; }
very important pattern for SOs
it lets you save data, publicly read it, and block things from trying to modify it
Why am I being yelled at? Trying to make my propeller spin
Have you configured 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
• Other/None
it's a formatting error. make sure your !ide is configured properly to receive errors in your coding environment . . .
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
• Other/None
simple formatting
syntax errors, you mean
the compiler doesn't care if your code is horrifically formatted, but it does care if what you wrote isn't valid C# at all
int x = 3; // bad formatting
int x = ; // bad syntax
syntax errors will be highlighted by your IDE, assuming that it is set up correctly
Like made sure it's what my default compilier is?
Maybe I'm too new to get that
Or maybe I understand and have forgotten
Nothing to do with formatting
Click the link for your code editor and follow the instructions.
do you receive the error message from your IDE? if not, then follow the link to complete the configuration . . .
the second line has an unexpected ; where C# was expecting an expression
thus the compiler yells at me
The point is to configure your code editor to show you errors, syntax highlighting, autocomplete etc.
same difference (not really)? 😅
no, I would not call a syntax error a "formatting error"
not formatted for PC xD
jk ofc
yeah, i joke. it was wrong . . .
I wasn't having any errors until I added the SpinPropellerX script and then it took a dump
And the external tools keep changing back to default rather than staying on VS
then you pasted it wrong
yes, the errors state that you are missing or have incorrect syntax, meaning, it was not typed correctly . . .
alright I will remove the script and see if it fixes. It's probably the weay I wrote it
there is no need to remove it; just fix the errors within the script . . .
Didn't paste it, tried to do it without C/P feels more accomplishing
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To 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.
as long your IDE is configured
Bahhhh, but errors suck DX
how could I start to go about creating two separate sprites which scale to the mouse. My current code is this . I just need a pointer since im pretty lost with my current knowledge:
public class StretchToMouse : MonoBehaviour
{
Vector3 mouseWorldPosition;
[SerializeField] Camera firingCamera;
[SerializeField] WeaponFire weaponFire;
[SerializeField]Transform Band_L;
[SerializeField]Transform Band_R;
Vector2 lPos;
Vector2 rPos;
float maxLength;
void Start()
{
maxLength = weaponFire.maxLength;
}
Vector3 GetMousePos()
{
mouseWorldPosition = firingCamera.ScreenToWorldPoint(Input.mousePosition);
mouseWorldPosition.z = 0f;
return mouseWorldPosition;
}
// Update is called once per frame
void Update()
{
GetMousePos();
Vector2 Ldirection = new Vector2(mouseWorldPosition.x = Band_L.position.x, mouseWorldPosition.y - Band_L.position.y);
Vector2 Rdirection = new Vector2(mouseWorldPosition.x = Band_R.position.x, mouseWorldPosition.y - Band_R.position.y);
Band_L.up = Ldirection;
Band_R.up = Rdirection;
lPos = Band_L.transform.position;
rPos = Band_R.transform.position;
float lengthtoBand_L = mouseWorldPosition.magnitude - lPos.magnitude;
float lengthtoBand_R = mouseWorldPosition.magnitude - rPos.magnitude;
float diffbetweenBands = lengthtoBand_R - lengthtoBand_L;
if (lengthtoBand_L <= maxLength)
{
Band_L.localScale.z = lengthToBand_L;
}
}
}
the error message(s) tell you the script and line number where the error occurs . . .
help, its not letting me drag the hitpoints script (the script I made into a SO) into the ES slot (an instance I made for SpawnManagerScriptableObject)
that's any type of development. you get an error, then fix it . . .
Right, but I can't seem to figure out how to correct it. I'll keep at it and try to figure out the actual problem rather than just eliminate the entire script
Why do you keep ...... Lol
Are you trying to drag in the actual script file itself?
Create an SO asset of that type instead, then drag it in
you have to create an asset of the SO and drag it to the variable slot to reference it, not the actual script file you created for the SO . . .
Yeah, thanks for the obvious answer lmao.
do you understand what the error is telling you? also, provide the code the error is pointing to . . .
this wasn't answer, just a statement (reply) to your post . . .
That's the part I'm trying to figure out friend. I don't know all the errors and stuff yet. I'm just starting
One second let me get another ss
so start with the basics of C#
you lack fundamentals
Dude I'm literally using Uinty Learn
dont get so defensive
Junior programmer.
mb
I'm not? lol
knowing the correct syntax is part of coding
no, the error in unity tells you what is wrong. if you do not understand the first error from your image, then i suggest to start with learning the basics of c# as it's one of the first things you learn . . .
Exactly why I came here to ask for help. Feels like I'm being attacked instead
this will be significantly easier if you have a working code editor
so which editor are you currently using?
relatable
bro what
lay off
use a bin/paste site for large ~code or inline formatting to post small code blocks . . .
Don't blame me then, blame Unity Learn. That's where I'm learning the fundamentals of C#
Unity learn is to learn the editor
it also covers the basics of programming.
you're new, so you're not familiar with how to ask questions
that's fine.
Didn't have any problems up until coding a spinning propeller. Managed to fix all the errors that the plane challenge threw at me
huh? i doubt they—Unity—made this error, though i'm blaming no one . . .
Using VS
facts . . .
vscode solos
or 
Lmfao, I was asking cult, not your opinions hahaha
the icons do not help at all
Purple one'
blue is VSC, purple is VS
rip
