#💻┃code-beginner
1 messages · Page 536 of 1
worst case scenario you just make multiple fixed timesteps
you can use a faster one for this
if you need a super slow one for something else
The higher the timestep the slower the fixedupdate runs so it's easier to press & release the mouse between fixedupdates
since you are using fixedupdate you should use impulse or velocitychange force modes
using default in fixedupdate will result in very small velocity change
I think?
This is...sort of correct?
Impulse and VelocityChange apply an instantaneous change in momentum or velocity
You're meant to use these for things like jumping
if (doTheJump) {
rb.AddForce(Vector3.up * 10, ForceMode.VelocityChange);
}
This is basically identical to
rb.velocity += Vector3.up * 10;
If you use these two force modes in every single fixed update call, you'll get 50 times more force or velocity change than you expected
void FixedUpdate() {
rb.AddForce(Vector3.up, ForceMode.VelocityChange);
}
This will accelerate you by 50 meters per second every second
void FixedUpdate() {
rb.AddForce(Vector3.up, ForceMode.Acceleration);
}
This will accelerate you by 1 meter per second every second
(assuming that your physics timestep is 0.02 seconds, of course)
It's wrong, but at least it's wrong in a framerate-independent manner 😉
It would be very wrong if you did that in Update, because then the amount of acceleration would depend on your framerate
I thought force was scaled by deltatime?
What’s the point of them even existing if they’re done by fixeddeltatime then
There are different force modes for different purposes
Um yes I’m saying the force and accel modes are just like
Velocity change * 0.02 or whatever ur fixed step is at
Surprised they even exist if that’s the case is all
Acceleration is so you can literally write the amount of acceleration you want in sensible units and it just works
Force is so you can literally write the force you want in newtons and it just works.
Acceleration is m/s^2
Force is in Newtons
It's possible to achieve the same result with any force mode but these are convenient for simplifying the math
Force and Acceleration apply x amount of force over time
Impulse and VelocityChange apply x amount of force during the one frame . . .
Those dropdowns are just shortcuts for adding and removing behaviours. Setting it to None just destroys the CinemachinePositionComposer behaviour, so that's what your code would need to do. However, that is not the recommended way to use Cinemachine. Instead, create a second CinemachineCamera without the PositionComposer and activate it.
i have a problem where script is working when i out game object manually in the hierarchy. but when i try to instansiate it it doesnt work/ i have checked prefab and the gameobject is same
Force: Continuous, mass-dependent
Acceleration: Continuous, mass-independent
Impulse: Instant, mass-dependent
VelocityChange: Instant, mass-independent
This is correct, though.
(at least when called in FixedUpdate -- I do not remember what happens if you apply a continuous force in Update)
I vaguely remember something being wrong
try logging more information to the console:
- select the current slime (you are shooting) from the hierarchy to look at its health, or log its health to check the value
- log when the
Splitmethod is called to check if execution reached that point (before spawning small slimes) - log the parent of the instantiated small slime to check which (original) slime it came from . . .
bruh im getting this silly error
so in this case what do i do
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
i did that yesterday and it didnt change anything
configure it
how is configuring done
did you click the links sent to you
click VS Code
double check each step is taken care of
it is
well obviously something is wrong. Close VSCode, go to external tools in Unity and click Regen Project Files button. Open script again by double click in unity
check for errors in vsc
its not giving me the thing that helps in code and autofills
Yes, I'm well aware. That doesn't not change what I suggested you do.. did you do the steps I told you ?
yes
make a video. Show me
just show me you doing the steps I told you above
Quick question, I was hoping to detect a null reference for a condition (if this doesn't exist yet, do something else first). Is there any way I can write a condition that evaluates that?
you can compare any reference type to null
if (foo == null) {
}
additionally, any Unity Object can convert into a boolean, so you can do
if (foo) {
// it's a valid Unity Object reference
}
if (!foo) {
// it's invalid
}
lol - why did you hide which external editor you have set in Unity? 🙂
you had vscode open first while I asked you close it before clicking the button. it probably cant connect vsc properly rn because of your compile error
Oh, that's a very important note
If there are compile errors in your project, new packages can't have their code compiled
oh i forgot its set to this
So they can't start doing things
If you have had errors since you started trying to get your IDE working, then you need to fix them (probably just comment everything out) so that Unity can actually compile
so im just gonna remove the line of code with the error for now
yes
fix ide first
then you can use a fixed ide to let it Offer suggestion to fix the error in code
it doesnt autofill still
no. now just try redoing the steps. close vscode this time, check off the first two also cause i think its default "Embedded packages" and "Local Packages" click Regen. Double click a script from unity.
check the vsc console /output for any errors
you must be able to enter play mode before continuing -- that proves you have no compile errors
might be
wait till the bottom loads
it should say either Assembly-Csharp or an error
and how long does that usually take
are these apps gonna affect it
is that AOE 3 open?
also I have literally no way of telling you how fast your own pc is lol. Everything you have open affects the memory/speed of course
thats age of history 3 different strategy game
its fast but i think i will close some stuff
is still not loaded?
I can't imagine it would take more than 5 minutes to connect to your editor of choice worst case scenario
if its stuck or not loading then yea you have to check what the output / log window
its still loading
I think theres another issue imo
could just be corrupt .net sdk
it says this
Could be. I havent read the entire convo. Did they have the VS studio package installed?
yes and fully up to date
Oh...They need the Runtime
the sdk installs both, runtime an sdk
wouldn't hurt to reinstall .net sdk
https://dotnet.microsoft.com/en-us/download
ok ig i will reinstall it
I'd just close everything and reinstall the needed dependencies
mehh thats preference
I dont need a bulky editor sometimes
.9 or .8
VS is also chunky, and bloated
fair enough
also if you work on mac, VS is gone
well the new 2022 is pretty fast
I just prefer lighter editors. Its all preferences, they all work for most hobbyists
i even saw people coding in the plain text editor
i saw a sophomore student programming in Microsoft Word
me on vim or nano 🥲
Word oh wow that is new to me lol
do i just switch to community
or does that have nothing to do with unity
if you want?
VS is "better" that VSC
community = free version
whats the difference
you're not a corporation or business so no worry
VSC is a glorified text editor
there's a paid version? 
always has been
as if anyone would pay money for it 😉
businesses have to..
if my indie game makes money do i need to pay for visual studio?
sure if its commercially used (and certain threshold is met)
so to switch what do i have to do
I use Rider (and paid for it, since I'm doing commercial work)
Pretty damn good IDE. I used VSC for a long time.
It's the only way I've been able to edit ShaderLab properly on my mac
the open source license is very nice of them
Enterprise organizations are defined as >250 PCs or > $1 Million US Dollars in annual revenue.
Can't find what the threshold for Professional is
install VS and then follow the guide below
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
ok
do they have telemetry in it that watches what code i'm writing, or my project names or whatever? cause isn't that the only way they can get someone to pay them
hi, i need help changing the shape of a collider box. I can provide a picture. I just need it to have an extended cuboid shape
oh wow, i had no idea, and i wouldnt be surprised if all these indie devs who made that much money with a unity game never paid for that
they might, for the most part is probably something you really do in good faith .. maybe .. no clue how they track it
You start paying more attention to this stuff when you have a good chunk of money
i just need the box to extend into the corridor
Perhaps you just want to add a Box Collider
that doesn't work for what i need. Theres game states for ambience for outside and inside. When using 2 seperate collidors, the outside ambience leaks in for a second when switching collider
damn i can't even find what the threshold is for visual studio professional, they've really made this stuff hidden
what extention do i download for visual studio community to work with unity since i already have it installed
!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
bro don´t understand it wrong but you can also use google or other source for most of your questions.
it is really easy
ok
anyone?
You'd get rid of the MeshCollider entirely
Alternatively, you should change your system so that it plays the internal audio as long as any of the colliders are being overlapped
perhaps by counting up and down when you enter and leave colliders
thanks
Can anyone help me? I'm trying to make my camera controller follow the player, but I keep getting this error? I'm new to C# and need to complete an assignment for my class. Anyone know a fix? Ill provide the script below! I am using visual studio and Unity
!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.
taking pictures of your screen is like, the worst way to share your code
Oh is it? I'm sorry, Ill write it down
How do I share it?
that'll just make it subtly different from the original
Ah I see
you would just copy and paste the original into one of the sharing sites listed above
but before that
just show the error itself please
Sure!
with screenshots, not with a picture of the screen
and show a stacktrace if one exists
Ah I'm not quite sure what a stacktrace is, but I'll do my best to provide better info with clearer images, thank you!
click on the error in the console, if it shows a bunch of files and method names, that's a stacktrace
(i can explain what a stacktrace is/means later, but it might take a while given you're a beginner, so i'll leave that for later so we can go over the error first)
I'm not quite sure how to utilize the link you sent me, would it be alright to send over the information here?
And I appreciate the help thank you!
the links there are for posting code, send a screenshot of the error stacktrace here
I sent it!
No I didn't destroy my player, I'm not sure why its giving me this error, I have a copy of the script if you need to see it
I'm not sure, I don't remember adding that should I delete it? For the most part I copied a tutorial video. So I didn't create the code from scratch 😭
check to see if you have other instances of cameracontroller, maybe
i believe i fixed it. I didn't fully grasp the logic of state groups. Essentially, when leaving the first mesh, i had it switch to outside ambience since it needed to do that when leaving the building. But this would mean it would also trigger briefly when moving to the corridor. So essentially what i did was remove all references to outside ambience while in those meshes and added a new box collidor by the entrance with the sole purpose of retriggering the outside ambience. A simple fix
ah, is "state group" a Wwise thing?
yes
I'm not familiar with that system
fair
I presume you could still do this, though -- you might just need to manually tell Wwise to change states, instead of having it automatically do it based on a single collider
i'm doing it for uni, music tech. They're making us use unity. I've never used unity before. Getting my way through it though.
idk. This works so me happy
ah, I see!
I've been curious, does everyone write their own scripts. Or do you find something similar and modify it?
i figured everyone wrote their own. that's what i do. it only seems normal . . .
No I don't :((
"everyone" does different things.
Beginners tend to copy-and-modify because they have no idea how to start
but once you learn the ropes, you write your own
There is one case where I do wind up modifying existing code -- when I'm doing something weird with someone else's library
I've made a few edits to the unity splines package to make it perform better for me, for example
(I need to NOT aggressively recalculate the up-vector cache on splines that are changing every single frame!)
Thanks guys.
Would you like to see my code maybe that's the issue?
Hi, i just started learning how to use Unity. I'm currently trying to use a tileset to make a 2d platformer but there's this bug that showed up where if I run on a flat surface, my character still gains some vertical height and goes into a jump state
I was wondering if its a problem with the collisions on the tiles? or the code of my player movement
this is my code for my player movement, as well as the colliding components i added to my tilemap
You're colliding with the corners between colliders. It's a common problem. The best solution is to use a single TilemapCollider for example
instead of multiple collidrs
is it the tilemap Collider2D?
Yes
Here's a thread about this issue btw
There's not a single "one-size-fits-all" perfect solution
Also look at CompositeCollider2D
i dont understand why but my camera is locking to offset(0, 5, -7) every time i press V, and its not locking to offset(0, 2, 1) at all
Look at the logic of your code
your logic is all wrong
why?
step through the code line by line
oh
i think i get it
is it that if i press V, its changing to true but then instantly to false cuz when its true and get's an V input its going back to false?
It's not changing to false at all.
When you press V ALL 3 of the If statrments become true
huh?
post your !code correctly and I'll show you
📃 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.
OK. So
if (camCheck == false && Input.GetKeyDown(KeyCode.V)) is this true? Yes camCheck is false and V has been pressed
so set camCheck = true
next step
if (camCheck == true) is this true? yes, we just set it
next step
if (camCheck == true && Input.GetKeyDown(KeyCode.V)) is this true? yes
so
camCheck = false;
offset.Set(0, 5, -7);
so although you set offset.Set(0, 2, 1); is is only for one if statement
okay i think i get it now thank you
it's easier to paste your !code using one of the sites so anyone call look at all of it, instead of separate pictures for each section . . .
📃 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.
what im i doing wrong when i have a valid tile my ui opens and want to be able to place a building of my choice wich i am trying to set in PlaceDefensebuilding but it doesn t wanna place seems like my button doesn t respond to the klick event but don t know why
just had 2 pictures didn t think it was that much but keep it in mind
so what are you using now
also i want to have a script that has a list of prefabs is there a way so that every gameObject already has that last of prefabs by defualt
VS Code
cool
Hey, is there a way to find inactive gameobjects by tag?
short answer: no
long answer: yes, but not with using tag methods . . .
Problem solved
If you made a singleton class that contains the list, that will be a fairly easy way to allow the list to be available to everything
But I used FindObjectOfType<T>(bool includeInactive) and everything worked
i also want it so that every gameObject that has this script i want the gameobjects in the list to have different values for each gameObject so lets say one gameObject upgrades the level so not all upgrade
yes, that is fine. as i said, you can, but not using unity's tag methods . . .
can you explain please
I think I get what youre doing, but you might have to clarify
i have these cities/states/provinces whatever you want to call them
anyone 🙃
place building is also there with an if statement btw
So its like you have 50 game objects (one for each state), and you want every state to have a list of every other state. That makes sense so far
each city has buildings and i want it so if u upgrade in one city it wont upgrade in the other
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
there are two methods:
- make the list static so every other script can access that list
- create a ScriptableObject with a list field. make a script with a field (variable) to reference this SO, and place the script on every GameObject you want to have access . . .
so what is the error ?
i have no errors at the moment it just doesn t work 😅
what is supposed to do?
wat is the word for c sharp for a codeblock?
As long as you create a different instance of each of your province gameobjects, you'll be able to different things with each instance without it altering the same thing in every instance you have
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Tilemaps;
public class PlaceDefenseBuilding : MonoBehaviour
{
[SerializeField] private GameObject buildingPrefab;
[SerializeField] private Tilemap tilemap;
[SerializeField] private Button PlaceBuildingButton;
public void PlaceBuilding(Vector3Int cellPosition)
{
Vector3 cellWorldPosition = tilemap.GetCellCenterWorld(cellPosition);
if (buildingPrefab != null && PlaceBuildingButton != null)
{
Instantiate(buildingPrefab, cellWorldPosition, Quaternion.identity);
Debug.Log($"Gebouw geplaatst op {cellWorldPosition}");
}
else
{
Debug.LogError("Geen gebouw prefab toegewezen in BuildingPlacer!");
}
}
}
but wont scriptable objects upgrade the building for all cities
only if you accidentally made static instances
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3Int clickedCell = PointedCell;
TileBase tile = tilemap.GetTile(clickedCell);
if (tile == expected)
{
Debug.Log("Je hebt op een verwachte tegel geklikt!");
if (BuyScreen != null)
{
BuyScreen.ShowPanel();
}
if (placeDefenseBuilding != null)
{
placeDefenseBuilding.PlaceBuilding(PointedCell);
}
}
}
}
hows this relate to showPanel
they are different gameObjects
tile is valid>showgui>click the tower you want>tower gets placed
debug your tile and expected , and check with logs
ah, but a GameObject is just a class, and if you have a static copy of a class, you'll have 2 different class instances but as theyre static, it'll actually be like you only have 1 object with 2 clones
but everything works just placing the tower doesn t work 😅
you have to log things
log what the true values are vs wat you expect them to be
think the problem lies with the button because it worked before when i didn t use the buyui
using an SO was suggested because you wanted every GameObject to have access to the same list. this helps because you have one instance of the list (in the SO) but give access to every GameObject that has the script attached to it
now you have further explained smth that may not suite this option . . .
and how so ? that button is not doing anything
yeah..
should i get the building system to work first then i work on making stuff its own for each city?
you can't make static instances. a static class cannot be instantiated . . .
People often confuse static classes with static references to an instance of a class.
The latter being more common
i see what you're doing. you want each city to have their own buildings and update them independently of other cities, but you want a (prefab) list of all possible buildings that each city can construct, correct?
exactly
me personally, taking the example of the US map, what I would do is focus on creating my "Province" class and just give it a string property like public string myName so each can have a different name.
Then if I can create 5 different instances of the class, make sure each has their own name, that proves the first part works
As I know each can be given a different name, I know changing one province isnt going to mess anything else up
we call them "states" here 😜
yeah, but "State" has more technical meaning behind it
they are called governates in my area but i already handled the province name part i just have the building left
then, when the player selects a building to construct, you would use the prefab from the list and instantiate that prefab. this will return a copy (instance) of that prefab. make sure to assign this instance to a field or list on your city (to keep track of it) . . .
ok
the first thing im gonna do rn is first of all try to think how i can even make the buildings show in the tab
buildings in tabs whats that
Wait... does that mean the USA is a Finite State Machine
navarone do you have any idea how i can fix it really don t know 😅
inspector list, I assume
oh
you don't tell me the result of the debuging how can i possibly help
i don't have eyes/mouse on ur pc
I mean, I'm assuming, I dont know for sure 😅
im thinking about making one of those scroll wheel things and it adds a button for each building that exists or something
don t know what more to do the placebuilding func just doesn t seem to be triggered have logs on it but they don t react
foreach(building in buildings){ var uiBuildingElement = Instantiate(uiElement, verticalLayoutGroupTransform); uiBuildingElement.SetStats(bla); }
you have to find out why. thats the whole point of debugging, its not just putting debug.log
is the thing called a scroll view
but there is no bug
I would do a ScrollView + VeritcalStackLayout in the Content section
alright i will try to do that to start
debugging doesnt just mean "look for bugs" it means also to find out why something is not working as expected
you have to find out why your code is not getting called
or why a certain function you made is not working like expected (e.g position or rotation being wrong)
If there is no bug then why are you here
I think you don't know what "bug" means if you think that.
debugging is fixing some behaviour from code that works but does the wrong action imo
A bug is any unintended/undesired behavior in software
Debugging is the process of finding the cause of and fixing bugs.
So, if the code is doing what you want it to do, then what's the issue
but it does nothing so that isn t unintended ig
So then what is the problem
It's not doing the thing you intend. So it's not intended.
you just said it doesn't work
placebuilding func just doesn t seem to be triggered
Dispel the idea from your mind that "bug == red text ERROR"
that's not what it means at all
but then is writing code also debugging unless you copy paste and it works instantly
No, debugging is the process of eliminating wrong behavior from the written code.
debugging is definitely part of the process of writing code though
i am trying to place a building when the player clicks a wreckege player clicks wreckege>ui spawns> player clicks desired building> building spawns and it goes wrong with clicking
Okay, so it has a bug
i see it as code not working not as a bug but whatever 🙂
That is literally what bug means
undesired effect, means it is a bug
If it's not working the way you want it to. Then it has a bug.
"I see this pile of meat and cheese in between two slices of bread and not a sandwich but whatever 🙂 "
you don't know what it is yet lol it can be code or even poor configuration of some inspector value. Unintended behavior is the bug
i kinda hope this is a game about explaining tariffs: showing how American companies can choose to pay for them or find a cheaper competitor to buy from, the loss in revenue from said tariffs, then eventually increasing prices to recoup losses or maintain their current price, thus adding to inflation
make sure the player has the option to build factories to try to increase jobs that will lead to economic growth in their region. of course there are other factors to input, but it'd be an interesting concept for players to experience themselves . . .
but how do you calls code wich doesn t do what you want vs does nothing than?
If you don't intend the code to do nothing, the code doing nothing is also a bug
how do you know the code is even being called? are you just assuming ?
this is a game about making and collecting nukes and yes the factories will help in ecenomic growth!!!
🤦♀️ omg, i wasn't that far off . . . 😂 🤣
Can Somebody Help me With my Jumping Mechanics pls, The problem is that i can still jump even tho i m not on a game object with a tag called ground, This is the code:
!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.
if you plan on showing us logs can you please at least make them english..
and trading with other countries
it says you clicked the button
thats not how OnCollisionEnter works. you don't call it
ohh
but also the call does nothing :/
That's a pretty odd way of doing ground detection. You're just checking if any ground exists anywhere?
you should just go with a simple raycast/overlap/cast
simple, you look them up and see how others do it
learn by someone whos been there before. 
If the second log isn't printing, then placeDefenseBuilding is null
but it is on the canvas button
yah ur right
btw remove that collab package, its old thats why its making error for plastic.
thnx tho
This doesn't show anything relevant.
On the script that has the bug, placeDefenseBuilding is null
how do i do that?
i just don t understand why it isn t valid
Where do you assign placeDefenseBuilding
do it after this problem is solved but.. in Package Manager , find the packages In Project and you find that one called collab n remove it
what do you mean with assign?
I mean assign
like this? because i think it is wrong
where is placeDefenseBuilding assigned
don't see any placeDefenseBuilding there
but that is the scripts name
What? Where do you assign the variable
What is the value of placeDefenseBuilding
its a variable you made for that type, where did you give it value
placedefensebuilding is a script and doesn t have a value only func placebuilding has?
No, the variable
placeDefenseBuilding
where? placeDefenseBuilding is a variable
where do you assign that variable a value
This has absolutely nothing to do with the question we are asking
in the code that isn't doing what you expect, you have a variable placeDefenseBuilding
What
the class is the type you chose for the placeDefenseBuilding it doesn't tell us how you assigned value to it
pointedcell?
No
placeDefenseBuilding
the thing I've said
like twenty times
that you screenshotted
literally ten seconds ago
that one
what is the value of placeDefenseBuilding
[SerializeField] private PlaceDefenseBuilding placeDefenseBuilding;
where do you give it value
thats declaring it, where do you assign a value.
nowhere then 
so it is null
and the log you said isn't running
only runs when the variable isn't null
so that would explain
why it is not running
but why doesn t the else come in clutch then?
What else?
There's no else in the screenshot you sent
om mb different script should have placed an else
btw you can also use grid layout inside scroll, iirc either way you have to mess with content size fitters to use it in the scrollrect
my only problem right now is figuring how so for each button its below the other
yeah you want to stack them ? use vertical layoutgroup
using UnityEngine;
using UnityEngine.Tilemaps;
public class TileChecker : MonoBehaviour
{
[SerializeField] private TileBase expected;
[SerializeField] private Tilemap tilemap;
[SerializeField] private BuyScreen BuyScreen;
[SerializeField] private PlaceDefenseBuilding placeDefenseBuilding;
private Vector3Int PointedCell
{
get
{
Vector2 screenPos = Input.mousePosition;
Vector3 worldPos = Camera.main.ScreenToWorldPoint(screenPos);
worldPos.z = 0;
return tilemap.WorldToCell(worldPos);
}
}
public bool IsValid(Vector3 mouseWorld)
{
Vector3Int cell = tilemap.WorldToCell(mouseWorld);
TileBase tile = tilemap.GetTile(cell);
return tile == expected;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3Int clickedCell = PointedCell;
TileBase tile = tilemap.GetTile(clickedCell);
if (tile == expected)
{
Debug.Log("Je hebt op een verwachte tegel geklikt!");
if (BuyScreen != null)
{
BuyScreen.ShowPanel();
}
if (placeDefenseBuilding != null)
{
expected.PlaceBuilding(PointedCell);
Debug.Log("you clicked the button");
}
}
}
}
}
but then i sort of gotta use expected?
baseTile doesnt have such method "PlaceBuilding"
no you use SetTile if you are putting a tile on tilemap
where do i add this component
the parent object that holds all your buttons for buildings
ok
so my place building func is not needed?
i dont even know what it does since that doesnt make sense coming from TileBase
if it needs to be a prefab use Instantiate and place it with WorldToCell / CellCenter or whatever.
if its a tile in tilemap then use tilemap.SetTile(pos, tileYouWant)
Hello everyone, i am confused about my code:
I can move fine in all directions using the keyboard.
But for some reason , when i use my dualshock 4, i can only move horizontally, but not vertically, why is that???
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 10.0f;
public float jumpForce = 50;
private Rigidbody playerRb;
// Start is called before the first frame update
void Start()
{
playerRb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
float verticalInput = Input.GetAxis("Vertical");
float horizontalInput = Input.GetAxis("Horizontal");
playerRb.AddForce(Vector3.forward * speed * verticalInput * Time.deltaTime);
playerRb.AddForce(Vector3.right * speed * horizontalInput * Time.deltaTime);
}
}```
AddForce never goes in Uodate. Only FixedUpdate
why? (i'm asking to undersatnd better, not to disagree with you)
unless you use impulse ofc (like a 1frame jump not constant)
Vector3.forward would move it horizontally
Because Unity uses a fixed-timestep physics simulation and if you want your code to behave predictably and consistently you need your code to run at that same cadence
why?
Using Time.deltaTime is not a replacement for that when it comes to physics and other simulations that have second-order functions-over-time in them like acceleration/velocity
deltaTime (or rather FixedDeltaTime) is already accounted for in the various ForceModes used in AddForce
what you are adding is extra noise that makes the units of the force you're adding nonsensical and unpredictable
By default, the force you add is measured in Newtons
and expected to be added consistently over time in FixedUpdate
if (BuyScreen != null)
{
BuyScreen.ShowPanel();
tilemap.SetTile(clickedCell, expected);
}
but how can i make it work and have it dynamic so i can use it on all i just don t know anymore
OOOooh i didn't know addforce and ForceModes had already that built in! Very useful to know!!
need to work for all buildings
As for:
i can only move horizontally, but not vertically, why is that???
Because Vector3.forward and Vector3.right are both horizontal directions
you might think of them as "North" and "East"
what you want is Vector3.up if you want to go up.
"dynamic so i can use it on all "
huh ?
yeah?
explain. the issue
so i can choose one of the buildings and it gets placed on the wreckege
I feel like an idiot now, but that makes so much sense!
The tutorial i was following was doing a movement on a topdown view of the game while i was doing from a sideview, it makes sense why it worked for him and not for me.
well you have to store/grab the building selected in ShowPanel first.
Thank you both for answering my questions!
yeah but dunno how to structure it anymore and make it work
because you are doing something kinda beyond your skill level, this isn't exactly an easy topic. For example , you would typically use an event.. Open the panel, user selects, store it in some type of variable, use confirms, event / method fires to then place the tile
your set tile code has to "wait" till selection is done
the buttons have OnClick you can call set tile after thats clicked, you have to figure out which tile each building type ui corresponds to
how do i make stuff instantiate at the top
this is more of a #📲┃ui-ux question
probably fixing the alignment
that doesn t matter the player can choose that
huh what does the player have anything to do with what I said?
we're talking about code/ structuring . player has no relevance rn
this you have to figure out which tile each building type ui corresponds to
clicking a Tower Icon, how do you know you now selected Tower to use in the SetTile
don t understand the question
Hey guy, for the past week Ive been making 1 tiny project/ day to get more familiar with the Engine, it's going great but now I need to create projects with better practices such as using getter/setters, interfaces/scriptable objects, etc. i have 2 questions
- Where can I learn the best practices to apply in projects?
- Do you guys recommend a youtuber or someone who goes through best practices - sometimes im not sure what to look for, and how it would be 'best practice'
Thank you 🥳
okay you want the player to select a specific building ?
I get most of my info from Unity docs at the moment and it works wonders, just knowing what to search for is what im looking for before i fall into bad practice like leaving everything like a score in update()
no that is what i am saying i want him to choose and has to be dynamic so it isn t bind to 1 lv
will have multiple of those for different levels
the unitylearn website probably
along with general c# practices still apply in unity
Oh probably in the more intermediate section, I'll check it out 🥳
also unity blog site has some decent stuff / general knowledge articles unity related
guess i have 30 min today to fix it going to bed soon
idk what that means
like each level has building and the player can like in the picture i sent

can like ?
just press it and place it
okay so what I said stil applies
you have to know what you are pressing corrisponds to
i have no choice 🤷♂️
that didn't work, i should have clarified the type of game i'm making.
Vector3.up doesn't work as it makes my character go up in the air, that is not what i wanted so i changed back.
Look at the video, on the first part when the capsule is moving only sideways, i am actually using my controller and moving the joystick in CIRCLES, he should have moved farther and closer to the screen!
At the second part when the capsule does move in all directions is when i'm using my keyboard, all directions work!
what is going on here? why does it work for my keyboard and not my controller?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float speed = 10.0f;
public float jumpForce = 50;
private Rigidbody playerRb;
// Start is called before the first frame update
void Start()
{
playerRb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
float verticalInput = Input.GetAxis("Vertical");
float horizontalInput = Input.GetAxis("Horizontal");
playerRb.AddForce(Vector3.forward * speed * verticalInput);
playerRb.AddForce(Vector3.right * speed * horizontalInput);
}
}
"Instantiate(ButtonBuild, Spawn.transform.position,Quaternion.identity, Scroller.transform);" its not instantiating at spawn.transform.position"
like i try or fail will prob fail at the end anyway but have to make a 2d cliker in unity
in 1 week now (had 2 weeks)
you should've picked an easier project
there are pretty complex systems at work here, especially when that involves UI interactions
need to make 3 levels with 3 challenges each
i think this is the only hard thing (hopefully)
Whatever class this is doesn't have that class public
currently using Unity6
System.Drawing is private??/
never experienced that before
It's possible they intend you to use a non-parametric version that is
As the error says, at the very least Image<TPixel> is
TPixel is private
same for RGBA32
the class itself isnt
It's probably a silly question, but why is it when I give my game object the foo class as the component, its the foo's Update that gets called, not the Update from the base? I'm not too sure why this doesnt give me an error too, as I didnt override anything
public class foo : MyBase
{
void Update()
{
Debug.Log($"This gets printed");
}
}
public class MyBase : MonoBehaviour
{
void Update()
{
Debug.Log($"this, does not.");
}
}```
you have to manually call the base update . . .
ah, right
currently you can't because it's not virtual . . .
nor is it public or protected . . .
you need to allow the method to be overridden, and give it the appropiate access level . . .
f god im done for today 🙂
You should really be using virtual and override when overriding methods, and calling the base function ( base.Example()) in the override if you want that behaviour
if these functions were public/protected you would be seeing a warning
What I'm not sure if is which update is the ony I should be getting Unity to call, because if I can have 2 different update methods in both the derived and base class, only one should be called
Unity will call the more specific one, ie. the one in the inherited class. But it's bad to have an inheritance hierarchy and manually redefine functions like this
only that class' Update is called. the parent class is only called if you manually do so with base.Update as mentioned before . . .
I'm probably not going to do anything like this in my actual code, it just threw me that this wasnt giving a few errors. It felt like it shouldnt have been able to write it
Does virtual hold the same meaning than in C++ ?
I don't use C++
Fair enough, I'll look that up
It doesn't hold the same meaning at all, and actually after thinking about it twice, that's quite logical because virtual in C++ has a lot to do with pointers
huh? it's used the same way. at least, i used it as i would in C# . . .
The syntax is similar, however in older C++ versions (probably even newer ones, but I'm unsure), you can allow polymorphism without defining the method as virtual at all in mother class
However it will eventually prompt an issue depending on the context
There's nothing wrong with the code according to the C# compiler
Both the parent and child classes declare a private method named Update
i dont really see how this is related to your question of if they hold the same meaning. this doesnt change that the keyword essentially means the same thing, and almost has the same behaviour
I see what you mean, my question was mostly about the technical behavior behind, rather than semantic, I misphrased it
notably, Unity uses reflection to grab the Update method. It doesn't care about accessibility
which is why these methods still get called even when they're nominally private
If it weren't for reflection, there would be no way for this ambiguity to come up at all
either way, its the same. you would use virtual the same in c++ as you would c# here
the differences are very minor
C++ introduces about 30 ways to blow your entire leg off, but it's otherwise the same idea 🤭
erm guys
for some reason my unity c# code is NOT showing up
like at all
vhat do i do?
Open the solution explorer window/tab(should be accessible from view menu). Is there anything in it?
They are unloaded though. Do you have the ide configured correctly?
!vs
Try clicking the button in the warning
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
Just a FYI for anyone having that weird bug with Start(), Awake(), and Update() its been fixed peeps. There more on the release notes friends.
sup gang
I'm trying to clean up my code a little
in my if statement on top, I have that in parentheses.
Does it replace what I have in red so I can remove it?
Remove what's in red
Probably. Try it out and see.
if by replace you mean addcard being false and you are okay with everything in the new if statement then sure
thankssss
yes I had "DontAddCard" as my bool before and that in red was left there as "true" x)
but yup it does work nicely, thanks
looking for a scripter 2D URP junior am doing animations and sprites
!collab 👇
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
does anybody know how i could get the enemy target position to work in the target spawn point serializefield
thank you
I got this error when trying to export from localization string table to character set for Russian, anyone encountered this?
"OverflowException: Value was either too large or too small for an unsigned byte."
Oh huh, I didn’t know you could do that
Can you show the stack trace? Click on the message and look at the bottom of the console
I'm sorry, unity localization has an error when trying to parse Russian characters, with other languages like Japanese, French, Korean it's completely normal.
The error is coming from code that tries to parse a format string's selectors
"Like this: {0}"
If it finds a character it doesn't like, it tries to turn it into a byte and then display it
But if that character's encoded value is too big, it doesn't fit into a byte, so you get an error
Can you check for strings that include curly braces like that?
If you have, say, "oops {ü}", that might break
(i don't actually know if that's out of range, but that's the idea)
Hey, i'm having a bit of trouble changing a method bool, i don't think i understand how they work properly
i'm calling hte onSelected() method from another script and i can trigger it no problem, however isSelected's printing false
what gives?
sorry even though i looked through the documentation i still cant find a way to fix it no matter what i try
public bool isSelected
{
get => isThisSelected;
set { }
}
your set accessor does nothing
Ah, i see
If you don't want to let other classes set it, use private set
once again the main problem in my code was between my chair and the keyboard
Still, i don't fully understand how the bool accessor works
i just saw i can't really set a variable in an interface there
"in an interface"?
Thanks a lot for your help, I fixed the error when changing locale to Russian - Russia instead of Russian. Although I don't really understand how it worked.
i'm sorry, i'm still learning this as i go, but isSelected is a bool declared in an iSelectableFurniture interface which this class's pulling from
That's very odd.
apparently i can't just use the good old bool isSelected in the interface code, so i have to do bool isSelected {get; set;}
Ah, yes
but i don't really understand why, or how to use it
You cannot declare fields in an interface
public class Foo {
public bool field;
public bool Property1 => true;
public bool Property2
{
get => true;
}
public bool Property3
{
get
{
return field;
}
set
{
field = value;
}
}
}```
This class has one field and three different properties
the third property has both get and set accessors
I think you want to make the property only have a get accessor
public interface Selectable {
public bool IsSelected { get; }
}
public class Whatever : Selectable {
public bool IsSelected => selected;
private bool selected;
}
e.g.
Because I turned off smart string so it stopped the error, in fact it is still there and happens when using smart string, how can I replace these characters when it is one of the characters of the Russian alphabet? 🤕
Can you show an example of a string that has the curly braces in it?
It is strange that complex hieroglyphs of Japanese or Chinese do not have this error.
Like this {value:choose(0|1|2):Изменить|Подать\n<size=40>Бесплатный|Подать\n<size=50><sprite=0></size><size=40>150}
I use a lot of smart strings in localize so I'm not sure which key it's actually failing on
Hmm, that seems okay. It’s only a problem if you have cyrillic characters in places like “value” or “choose” or “0|1|2” here, I’m pretty sure
I see what you mean, I will check it again and hope it works.
It'd help if you could just make the Localization package print out the bad string
You could do that by embedding the package
I found it manually, I used the auto translate function in google sheets and it produced this string
Соответствует {количество} элементов
Thanks for taking the time to help me.
You'd copy /Library/PackageCache/com.unity.localization@1.5.3 into /Packages/com.unty.localization@1.5.3, then go and edit the function
ah, nice!
That sounds like a bug. I'll look at reporting that tomorrow
Prefab assets can't refer to components in the Scene
The in-scene component that instances your prefab can reference other in-Scene components, so have it pass your instance that reference.
lets say u have 3 int field that u can modify on inspector
public int A;
public int B;
public int C;```
if i turned them into an array
```cs
public int[] Array = new int[3];```
they cant keep the value from the inspector right?
you'd have to set them again, yeah
nope, just set them again . . .
there's nothing to indicate that A/B/C are linked to Array
also pretty sure you can't restrict the array size like that, setting an array in the inspector is an assignment, it'll just get replaced with whatever size array is set in the inspector
the problem is, everyone is being too lazy to do this, these variables are being used across 300+ objects with different values
but it can provide 3 fields by default right? like u dont need to press the + signs at the beginning
you can initially assign a length; that will be the default value. of course, once you change the length from the inspector, it uses the inspector values, but you can as a default . . .
yeah thats what i talking about
i can guarantee there will only be 3 fields needed
public int enFontSize = 60;
public int tcFontSize = 60;
public int scFontSize = 60;
public int[] FontSizeArray = new int[3];```
if u guys curious, thats what im doing now
ouch, now that sucks. just create a method and slap an attribute on it that allows you to call it from the inspector. have the method assign A to Array[0] and so on . . .
yeah this is the 1 out of 100+ things that need to be optimized
after you run the method and you check that each element is correctly copied, you can remove the three fields without worry . . .
i mean you can't restrict it by setting an initial length
no, not really, but it's possible by using a validator . . .
but then why are you using an array
oh, for sure, haha. typically, most people wouldn't do that. though, i will say there are some scenarios where you only want a finite length for an array . . .
a limit, maybe? but an exact length doesn't seem like a situation you'd want an array
wait, isn't that exactly why you want an array?
if you have an exact length, that could imply each member is a specific thing. a struct would probably be better for that
like this situation
why not use a class or smt then
yh
en/tc/sc FontSize aren't all interchangable, an array doesn't make sense for that. linear structures tend to be homogenous
not exactly, no
probably biggest usecase for using array in a scenario like this is to iterate over elements but I would assume you don't have to do that for smt like this
like u just want to set xyz text font size to enfontsize if its set to english right
to be honest the 3 variables way sounds better
u see there are enfont, tcfont and scfont right?
actually we have an enum that is correspond to them, if enum = 0 , we will change text = enfont , if enum = 1, tcfont.... and so on
so why the hell we dont use an array to do that at first place?
text.fontsize = FontArray[(int)enum]```
you can definitely do this right?
why not use a dict for that, so you can benefit from having an enum?
because u need to tune the value of the size, if u use dictionary u need to visualize it
and you can have a list/array of structs so you can use to initialize that dictionary, if you don't want to manually serialize it, so you can actually use the enum names
if you use a list or array to begin with, you don't see the enum order in the inspector, that's more prone to mistakes
also with the array, imagine you forget to set one of the values. how would you know which one you forgot to set
an indexed container doesn't make sense when your values are specific to each key, each enum key
YO WAIT, we actually have one script
u never know the whole picture of a 5+ yrs old project💩
lets ignore who joe is but hes awesome 👍
great, use that
[ExecuteInEditMode]
class temp : MonoBehaviour
{
private void Awake()
{
languageChangeText script = GetComponent<languageChangeText>();
script.FontSize = new FontSizeDictionary()
{
{ LanguageDataScript.LanguageCodeRes.ENG, script.enFontSize },
{ LanguageDataScript.LanguageCodeRes.CHT, script.tcFontSize },
{ LanguageDataScript.LanguageCodeRes.CHS, script.scFontSize }
};
Destroy(this);
}
}```
btw this is the script that i gonna put to generate the dictionary
that coderes is enum i mentioned
🤨 why's your component in camelCase
standard of our team 💀 💀 💀
is there a way to create a trailer that can act as a threshold to only call UpdateBakedMesh() when blendcounter is above itself + 2 or something
its pretty process intensive, but setting it to every 100 frames instead of every frame helps fps immensely
the standard is : for all naming, camelcase
actually no
we dont have standards 👍
if u really want one standard : as long as it can run with no errors
that's normal
wdym lmao, convention in c# and unity and many other languages is camelCase for both fields and locals
btw for exceute in edit mode script, can you destroy the script itself? like remove it from the object
destroy is not working tho, because its editor mode?
i do think execute in edit mode only scripts shouldnt follow monobehavior
like u just type functions and it will execute all of them at once
I mean it isn't
unity official docs literally say to use pascal case
got a link for that? couldn't find it with a quick search
for me , "fields" are just visible "variables", or like buttons on a control panel, they should follow what variables will be on public and private
Use pascal case for public fields, and use camel case for private variables: For an alternative to public fields, use properties with a public “getter” (see previous and following sections).
Consider
😂 #
ok buddy
of course its consider
they're conventions
not the language literally doesn't work if you don't
having a small prefixes or symbols in front of namespace is really not used to , my own style is Pascal for all enum classes, public variables, classes and functions
camel for all private/local variables
static follows public/private
fields are visible variables, they will follow what variable should be
yeah i really don't know what to make of that. even the examples in the scripting docs and pathways use camelCase 🤷 (ex)
i don't know of any other languages that use PascalCase for fields either tbh.
Using m_ lets you easily identify local vs class variables in a long method for example
but at least most ppl have came up to a common solution where Pascal and camel should be lol
but ive yet to see any docs that use PascalCase for fields
nor any code, really
using PascalCase for fields would make it overlap with types
love me some Rigidbody2D Rigidbody; Rigidbody = GetComponent<Rigidbody2D>();
welp....honestly myself dont have concepts of field and variables tho , in my mind, it was like this
class XXX{
public type A; // visible global variable
private type B; // hidden global variable
private type C; // hidden global variable
public void D(){
type E; //local variable
}
private void F(){
type G;//local variable
}```
💩
mfw im lazy and dont give the variable a descriptive name and it ends up not being a good name
the naming is more important tho lol
ur argument makes no sense
what if you wanted to use properties
which is very well accepted as pascal
...what else would you name the current gameobject's rigidbody
not in unity
for me its pascal yes
properties in unity are in camelCase too
unity uses properties a lot and they're all in camelCase
zzz ok i cba
i couldn't find any "fields" in the docs, i think they might be listed along with properties. ill go check one sec
nope seems like they're all properties
and they're all camelCase
hey, I Would Like Some Help With My camera and player system. the problem is that my player is not moving the direction the camera is facing, heres the code
unless your player is a child of the camera, the camera is rotating freely of the player
you need to apply yaw (horizontal rotation) to the player and pitch (vertical rotation) to the camera, and then have the camera inherit the yaw from the player
i have no idea what how to do that,
Simply move your player with tge forward and right of the camera transform instead of his own. Note that if your camera tilts you will have to project the vectors on a plane defined by the up of the player
hi im working on a project for class and so ive got a textmeshpro - text to keep track of the score but unity is saying it cant find it?
textmeshpro is a package. the text component is like, TMP_Text or something along those lines
did you import TMPro?
im p sure i did but ill double checlk
ah okay so i did import it initially into unity but not into visual studio
thank you!
into the script itself, not visual studio as a whole
err yes, i imported it into the script but that was the issue
You need to configure your !ide so you can easily fix basic issues like these, and get autocomplete and error highlighting
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
my code isnt showing up in visual studio, i asked yesterday but nothing helped
NEVA MIND WE FIXED IT
but i cant see code line numbers
like for example i cant see line 1, 2 etc
Doesn't really sound like a coding question, but something about your VS configuration in general
yeah its fine i worked my way around it but i still dont see them, its weird imo
just go enable them in vs options
I mean this specifically
Anyone have idea to implement this? so my bear ai can get shot because of box collider, when he died he play the dead animation, but box collider still active like he's alive. I need the box collider to adapt to bear dead animation because after the bear dead. player can loot by hit it with melee
Define the size of the hitbox for both states, and switch or interpolate between them.
Ahh okayyy
hello what to write next? because I want the character to have a double jump "else" and what next?
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
[SerializeField] bool isGrounded;
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if(Input.GetKey(KeyCode.R) && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
if (Input.GetKey(KeyCode.Space) && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
If you wrote this code yourself you would know what to do next. If there is an issue that prevents it from working I suggest you share that instead.
this script works as it needs but
i need add else
and then what next?
i just dont know what add after this if(Input.GetKey(KeyCode.R) && isGrounded) { velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
to do what?
double jump
ok, have you researched that at all?
If you want double jump, it's a matter of adding a boolean to check if you jumped once. Then, in your if-statement for jumping you want to check if you either jumped just once or you're grounded.
also, again, why do you have 2 ifs for the same action
that's going to make it impossible to do any branching conditionals
I suggest you simply add an integer for "jump count". Then when you succesfully jump you increment it. If you then try to jump again, check if the count is equal to 1, and allow a jump again. If it's 0, check for isGrounded. Lastly, 2 always fails
The only thing left is setting it back to 0 when you get grounded again.
i just add for test somethink and learn
how it work
if it's 0, check for
isGrounded
this would not quite work for falling of a ledge then jumping midair
would probably be better to add a bool for that single mid-air jump
i will try
The point is not really edge cases. That's up to them
Especially since there are plenty of things to consider here, and perhaps their game doesn't have ledges? 🤷♂️
TileScript choosenTile;
//* Grid Spawn Logic
if (choosenTile == null) { //Error use of unassigned local Var
var randomTile = UnityEngine.Random.Range(1,11) <= 9 ? _grassTile : _mountainTile;
choosenTile = randomTile;
}
Why do i get an error here? I want to check if it is null, why don't you let me? If i understand https://stackoverflow.com/questions/9609715/creating-nullable-class is corretly. Classes are automatly nullable, rigth? TileScript? choosenTile; Something like this also didn't work
Old .NET did not have nullabillity on reference types. Modern .NET does enforce this. I believe it's still disabled in Unity, but you can add #nullable enable at the top of your file to enable it
That said, your code is correct so I can only assume you have left out important bits. Please share all the code if you want to be helped.
The only thing I can assume is that this is a local variable, in which case you need to explicitly assign it to null
Right now you defined the variable, but it is not assigned
If use this, alot of yellow "Errors" appere.
-TileScript choosenTile;
+TileScript choosenTile = null;
Yes, because nullabillity is now actually enabled 😄
It's not complaining about checking against null. It's saying that you haven't assigned a value to the variable.
All those yellow lines are spots where a variable can potentially be null but you have not handled it that way
That worked
I do have to mention that in the case of Unity a lot can be wrong so I generally add it and then use what's called a "null-forgiving operator" on the spots that are incorrect.
Thanks
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
[SerializeField] bool isGrounded;
[SerializeField] bool secondJump;
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (!isGrounded)
secondJump = false;
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if (Input.GetKey(KeyCode.Space) && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
secondJump = true;
}
else if (Input.GetKey(KeyCode.Space) && secondJump)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
secondJump = false;
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}```
which line is wrong because I don't have an error and the character doesn't double jump
secondJump not working
you're making secondJump false when you jump the first time, instead of refreshing the jump
wait i will check
you don't need secondJump = true in the first check
also, use GetKeyDown instead of GetKey so it only triggers on the first frame that it's pressed instead of doing the second jump right after the first
In this case I would suggest you learn how to debug but it looks like the answer has been spoonfed already 👍
Perhaps you're still interested in learning a bit of debugging regardless, but that's up to you
thnk you
Heya, im testing around a bit with AI using tutorial vids and im running into an issue where my AI wont pick up the player game object, im not sure why since the player is called "Player" which is the same name that the game object finds and assigns but I keep getting null instead, any help would be greatly appreciated, my code for the AI is below.
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEditor.Rendering;
using UnityEngine;
using UnityEngine.AI;
public class RKTiMove : MonoBehaviour
{
public bool isHostile;
public Transform currentWayPoint;
[Space(12)]
public NavMeshAgent AiAgent;
GameObject Player;
[Space(12)]
public float distToPlayerAttack;
public float speed = 3;
// Start is called before the first frame update
void Start()
{
Player = GameObject.FindWithTag("Player");
if (Player == null) {
print("Player is null");
}
}
// Update is called once per frame
void Update()
{
if (!isHostile)
{
AiAgent.SetDestination(currentWayPoint.position);
return;
}else
{
print("Else statement worked");
float DistToPlayer = Vector3.Distance(transform.position, Player.transform.position);
if (DistToPlayer < distToPlayerAttack)
{
print("speed is 0 bozo");
AiAgent.speed = 0;
}
else
{
print("cooking the speed rn");
AiAgent.speed = speed;
}
AiAgent.SetDestination(Player.transform.position);
}
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, distToPlayerAttack);
}
}
print("Player is null");
This is printing?
Yeah
If that's printing then indeed you don't have an active GameObject named Player in the scene
At least, not at the moment this script's Start is running
Make sure you actually have such an object in the scene
maybe the enemy loads before the player?
oh sorry
you're using FindWithTag
not Find
So it needs to be tagged Player
ooh
In the future for posting code: !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.
The start order could definitely matter if you did something like this
thank you!
void Start() {
gameObject.tag = "Player";
}
and then elsewhere:
void Start() {
var whatever = GameObject.FindWithTag("Player");
}
gotta watch out for that kind of thing 😉
but yes, I think you're just missing the tag here!
actually where would i drag it since i dont see any specific Player thing here
Drag what
there's nothing to drag
nvm uhh i mean like how would i tag my player to it
You need your player object to have the "Player" tag.
Select the player object
and change its tag to Player
why not just set the tag in the inspector
its def working better
I was thinking about that :p
Thank you! got it working now
I'm using a CharacterController and ProBuilder and for some reason, OnCollisionEnter is never being called.
because CharacterController don't use OnCollisionEnter. It uses OnControllerColliderHit
That doesn't work either tho.
show code + setup
void OnControllerColliderHit(ControllerColliderHit hit)
{
LavaBounce bounce = hit.gameObject.GetComponent<LavaBounce>();
if (bounce)
{
Rigidbody playerRb = GetComponent<Rigidbody>();
playerRb.AddForce(Vector3.up * bounce.bounceForce, ForceMode.Impulse);
}
}```
i mean the code is just the void.
i don't know why it doesn't trigger
How do you know it's never being called
Have you put a log in the function? Maybe log bounce before it's checked?
I have put a log in yeah
I put a log to log just anything that collides and none of the Probuilder meshes are triggering it
by the way, why is that people are referring to functions as "void" nowadays? 🤔
it's a common error
Because they are wrong
And they don't know what "void" means
void is just the return type of the function
yes, but where does this comes from?
it's the only keyword in the function's declaration
other languages might make you write, say, func Foo() or something like that
Because they don't know what "void" means, and they assume it's just a magic thing that makes a function exist
geez okay
Show what you added
I just added Debug.Log(hit);
- Does the object with this script on it have a CharacterController?
- Does the other object that you're checking for
LavaBouncehave a collider?
The Player has a CharacterController yeah, and the other object has a Mesh Collider
it's a ProBuilder object so MeshCollider comes on it by default
and the component that this code is part of is attached to the same object as the CharacterController, right?
Yeah, the player capsule
is there any API in unity 3d texture that allows me to copy blocks of one texture image to another texture image with how i flip the image
to rule out it being something with ProBuilder, add a cube to the scene and try moving into it
Also, it's important to note that you have to move into the collider to get a message here. If you don't add gravity, and you're just walking around on a flat surface, you will not receive messages
Hey
Guys
I am having some trouble
i wanted to import image sharp library inside unity but there is a problem
i cant use the System.Runtime.Intrinsics
i thought unity6 uses Net 8
and Memory Intrinsics was defined in .Net 5+
I dont know what to do now
any helps are appreciated
and all i can find by googling Intrinsics is a C++ native memory intrinsics library that .Net have bindings for
If i have a class that has another class in it, something like this public class JokerShop : JokerBase
What's the term for this, is nested Class correct?(for future google searches ) And how to acces the JokerShop Class properly?``` JokerBase MyJoker = XY
Myjoker.JokerShop.DoSomethingThatsOnlyInJokerShop;
JokerShop MyJokerShop = MyJoker.Get-JokerShop(SubClass) and save as new Variable
Inheritence. JokerShop is a JokerBase. A variable that can hold a JokerBase can also hold a JokerShop
If you want to do something that is only in JokerShop, the variable needs to be of type JokerShop
If you want to check if an individual JokerBase is an instance of JokerShop specifically, use the keyword is
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/is
Thank you !
It worked on the cube, so it is an issue with ProBuilder.
Now you might have expected this, but the rigidbody AddForce part isn't working now, my character does have a Rigidbody, but all movement is handled through the Character Controller because this project was made using a first person game preset.
nested class is a different thing, it's exactly what it sounds like; a class inside another class (or some other type)
you usually won't need nested classes for unity, but sometimes nested structs can be useful.
so then how would I create a spring pad using Character Controller
You shouldn't have both a Rigidbody and a CharacterController on the same object.
The Rigidbody wants to move the object around after each physics update (if interpolation is off), whilst the CharacterController is moving whenever you tell it to
Does the behavior change if you make the mesh collider convex?
you shouldn't need to do that
No, it still does nothing
I guess I'd have to put an invisible cube over the ProBuilder object as a workaround.
You can look at the controller's velocity property. That tells you how fast it moved the last time you moved it (which was, hopefully, one frame ago)
You can use that to decide how much to move in the next frame
You could also just store a separate "spring velocity" that rapidly decays to zero over time
and add that into your movement each frame
Lots of options there -- you're inventing your own physics :p
You want to get at https://docs.unity3d.com/ScriptReference/RenderSettings.html
I don't remember how to fetch that..
Oh wait, they're all static properties!
So you'd do RenderSettings.fog = false; or whatever
New to Unity, I'm trying to figure out how to "project" a png with transparency onto whatever is nearest on its path. Ideally warping to whatever is currently below it.
Literal description is it's a crosshair shaped light projecting down onto a moving tray.
I tried setting up URP to do it but some of the assets I can't replace don't have compatible shaders for URP. If it matters, this is for a VR project.
Hi, I am trying to make a simple pick up and drop system where when the player looks at an item like a flash light and presses E the item is picked up and press Q to drop the item. This is my script just a simple ray cast how can I make it so when you look at an item and press E you pick the item and press Q to drop it. I am very confused on how to do it. https://paste.ofcode.org/FvimTSGeLNVhdN3t4asNLK
This sounds like a decal projector.
you could make a prefab of this flashlight and add it to your player, then remove the one the raycast hit then just do the opposite when pressing Q
That's URP, which I can't use
Ah, I misunderstood -- I thought you were using URP already
The built in render pipeline also has projectors https://docs.unity3d.com/Manual/prepare-materials-projection.html
hold on im abit confused so wdym add the prefab in to my player? like attach it?
you would instantiate it as a child of the player
you would also have to find which object the raaycast hit by either using a tag/layermask (not really recommended) or some other script which tells your grab script what it is
hi im super new to unity and i dont understand whats wrong with my code. can anyone help me?
what is the issue, as they're many
!ide do this before you get help here
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
⬆️ fix your ide so it underlines your typos
well then i say play it comes up with "all complier errors have to be fixed before you can enter playmode!"
configure your IDE using the link
we know, we can see your script has errors, configure your IDE since its impossible to code anything without doing that first
Note that, if you need to install a new package to get your IDE working properly, that won't be possible while you have compile errors.
You may need to get rid of the script to set that up properly
yeah but im dumb as hell i dont what a IDE is
(just move it out of your Assets folder)
also you do not need if(_Inputx != 0) as InputX will be zero already if not input is added, you are also using addforce in Update instead of FixedUpdate
an IDE is an integrated development environment
visual studio
a text editor that also has features like syntax highlighting and text suggestions
also unnecessary usage of getcomponent and assignment in the start function (just use the inspector)
that's a code editor btw
🙏
eh for the current gameobject it's fine
I mean if you don't need to get it on runtime just use the inpector to assign it
that would be the easiest solution
getting components on the current gameobject via getcomponent in start/awake is pretty standard
well yes, but that is for when you want to get it on runtime. I don't really see any need to do that except if you just don't want to do it manually
what need is there to do it via the inspector?
it is easier
but that is for when you want to get it on runtime.
no, static components are generally retrieved like this too
not really; that's quite subjective and imo it's a little more error-prone
if you put the wrong component into it yes, but you should know how to use the inspector and how to assign components through it
no, dragging the wrong component wouldn't be an issue.
dragging the wrong object would be
that's not an unreasonable mistake, just dragged the wrong object, and a beginner might not think to debug that
yes a wrong component from another gameobject , Also most people should know how to use their brains to figure out a problem, no?
it's an extra step that might result in bugs.
assigning it directly wouldn't. and forgetting either would result in an error either way
...have you seen beginners before
they don't know where to start
its critical thinking, and using the tools they have to figure out solutions
or you could recommend something that isn't likely to result in bugs
this is why you would teach them to use the inspector
also, like i said, stuff is generally done like this. if i saw a serialized field that wasn't assigned to, that was seemingly for a component of the current gameobject, i'd assume that was 2 mistakes, not an "alternate solution"
or you would teach them to use the inspector for stuff that should use the inspector
such as assigning a rigidbody and floats as they have in their script, also if you saw a field that was unassigned not only would unity tell you through errors it is as simple as dragging and dropping the correct component into it. I'm not saying the getcomponent method is bad but for this situation it would be better to use the inspector as that is what it is for.
this is also a good way to teach people to actually think instead of mindlessly doing things, as they will see the error and wonder how to fix it/tinker with it