#💻┃code-beginner
1 messages · Page 500 of 1
because thats what you named your variable
lol
the right one is what you named your bool, so it matters
the left one is what you named your variable, this can be anything
So I could put anything on the left rn and it would always work?
yes, but you need to change the name of your variable also
the one that you're referring to with this line of code
you declared a variable with a name, you have to use that same name to refer to it
you can name it almost whatever you want
But the bool IS the variable no?
you have 2 variables here
1 for the script
1 for the bool
How are they named the same thing then tho
because you named it that
No
yes
OHHH
exactly
Okay now I understand
I thought SchloppyLebt is used there so the current script knows that I want to use the bool
It's a variable name, you can call it what you want
ive been trying to explain this to you for 2 hours that this is not the case
Im so sorry man
i said it at least 5 times 😂
everytime you said that I didnt know what you meant bc you didnt specifically told me what you meant
Im so sorry
xD
The barrel of the cannon is not facing the enemy as it should and seems to adjust the base transform of the barrel. When I set the barrel's y rotation to 0, it isn't the same as 0 y rotation when I start editor playtesting.
GameObject target = GameObject.Find("Enemy_" + targetID);
if (target != null) {
Transform barrelTransform = transform.Find("Barrel");
if (barrelTransform != null) {
Vector3 direction = (target.transform.position - barrelTransform.position).normalized;
direction.y = 0;
Quaternion lookRotation = Quaternion.LookRotation(direction);
barrelTransform.rotation = Quaternion.Euler(-90, lookRotation.eulerAngles.y, -90);
}
else {
Debug.LogError("Barrel object not found.");
}
}
else {
Debug.LogError("Target not found.");
isTargeting = false;
}
}```
Any help is appreciated.
So after 4 hours I fixed the isssue and understood it.
Thank you guys. ❤️
<#💻┃code-beginner message> here i said it
probably confusing for you though
But for the future. People usually use the same Variable name so they know what they are using it for, right?
you should probably have a parent which its center would be located at the end of the barrel.
and rotate the parent instead
no
they use the script name usually
for example public Rigidbody2D rigidbody; is what i would use
i wouldnt use public Rigidbody2D velocity; just because i want to do velocity.velocity
So like this:
public SchloppyScipt SchloppyScipt;
?
The start of the barrel? Or at least its rotation point?
where you want it to rotate from, which i assume should be the edge of the barrel
Ahh okay
It shouldnt rotate around that point though
well rotating it at the center is also not what you want
Hows come? Is this just a workaround for the issue
i mean unless im understanding wrong?
Well I'm not understanding much about the issue as I have no clue why its happening
0 y rotation at the start of the project running and in the prefab editing mode is different than 0 y rotation after its tried looking towards a target
well you change the Z
Which makes 0 sense, like the origin is being changed in teh code
maybe thats why
the only difference in the 3 pictures you show i see is the z changed
the 2 pictures on the right are identical
Ok ill try that give me a few
🤷♂️@deft grail
A little bit more: the barrel slowly rotates towards that position without the Y changing at all, and then stays there
Is there any way to have a static variable show up in the inspector, because I want to have a static List of Items that any script can grab; but once I make it static, it disappears from the inspector, which means I can't add it. My only solution I can think of is like an in between a variable that isn't static, but when the game starts; it puts all the items into the static list.
make a static instance to the script instead? not sure if this is better but might be
someone can help me, post processing is not being applied
sorry
have decided to re-evaulate
should i use a rigidbody and attempt to code everything it doesnt do like a character controller
or should i use a character controller to get it to interact with physics
character controller can interact with physics
its a physics object anyway
i thought they ignored physics
its like a mix kinematic type controller
calls OnTriggerEnter methods and OnCharacterControllerHit
but like kinematic rb it ignores external physics forces though
in a frustrated rage of trying to figure out how to work with rigidbodies, i may have deleted a large chunk of my code
i probably have it saved somewhere
That's where you realize you should have used version control.
time to figure out what that is 
guys i need help with this
heres the script
wait
sending
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Inventory : MonoBehaviour
{
private const int SLOTS = 9;
private IList<InventorySlot> mSlots = new List<InventorySlot>();
public event EventHandler<InventoryEventArgs> ItemAdded;
public event EventHandler<InventoryEventArgs> ItemRemoved;
public event EventHandler<InventoryEventArgs> ItemUsed;
public Inventory()
{
for (int i = 0; i < SLOTS; i++)
{
mSlots.Add(new InventorySlot(i));
}
}
private InventorySlot FindStackableSlot(InventoryItemBase item)
{
foreach (InventorySlot slot in mSlots)
{
if (slot.IsStackable(item))
return slot;
}
return null;
}
private InventorySlot FindNextEmptySlot()
{
foreach (InventorySlot slot in mSlots)
{
if (slot.IsEmpty)
return slot;
}
return null;
}
public void AddItem(InventoryItemBase item)
{
InventorySlot freeSlot = FindStackableSlot(item);
if (freeSlot == null)
{
freeSlot = FindNextEmptySlot();
}
if (freeSlot != null)
{
freeSlot.AddItem(item);
if (ItemAdded != null)
{
ItemAdded(this, new InventoryEventArgs(item));
}
}
}
internal void UseItem(InventoryItemBase item)
{
if (ItemUsed != null)
{
ItemUsed(this, new InventoryEventArgs(item));
}
item.OnUse();
}
public void RemoveItem(InventoryItemBase item)
{
foreach (InventorySlot slot in mSlots)
{
if (slot.Remove(item))
{
if (ItemRemoved != null)
{
ItemRemoved(this, new InventoryEventArgs(item));
}
break;
}
}
}
}
eventhandler comesfrom the System namespace
oh so how do i fix it?
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
not likely and if it were you can use quick-refactor to add the namespace
im quiet new to this so can someone explain whats a namespace..... 💀
bet
So let me get this straight
if I have a Vector3(0f, 1f, 2f), would Vector3.normalized be (0f, 0.5f, 1f)?
No, it will make its length 1.
(0, 0.5, 1) has a length of more than 1
what would it be equal to then?
I'm not a calculator, why not test it yourself lol
fair enough
when would you usually use that though?
Vector normalization is simply dividing each of it's component by the vector magnitude
vector (1, 1, 1) -> magnitude √3 -> normalized vector (1/√3, 1/√3, 1/√3)
For example, when you want to get a direction, without it being affected by the distance between one object and another
Or when making diagonal movement the same speed as when walking up/down/left/right only
i see i see
yeah I was thinking of using it for charactercontroller movement
because I wanted a kind of "knockback" effect
thank you!
Thats one place to use it yeah. You probably dont want it to depend on the distance, just want the normalized direction
yeah, I basically want to take the direction from the enemy to the player, and add force in that direction
so yeah
this should be it
if it wasnt normalized itd probably make me get knocked back more or less, depending on the distance
which honestly, doesnt sound too bad, I could make that a mechanic
but yea
Depending on the type of game, it can be dependent on the distance, but probably not on the "raw" distance, i.e. if you want the knockback to be less effective if the enemy is too close or too far, you translate the distance into an appropriate modifier and multiply it with the normalized direction vector, that's one way to look at it
Sure.
But yeah, you basically want the normalized direction at the very least
although a different issue:
I'm using a charactercontroller to move the player, and if I call controller.Move() inside of fixedupdate, it jitters, while if I call it in update, it moves the character more/less depending on the framerate
Should use Time.deltaTime when calculating the movement in Update
I am
Show code?
or do you mean multiply the force with Time.deltaTime?
Yes
If by force you mean the value you pass into Move
a yea ur right
I mean this is the thing I have
void ControllerMove(){
forceToAdd = Vector3.Lerp(forceToAdd, Vector3.zero, Mathf.Pow(forceFraction, 100 * Time.deltaTime));
controller.Move(forceToAdd);
}
public void AddForce(Vector3 direction, float force){
forceToAdd += direction.normalized * force;
}
}```
and I call ControllerMove() in update
so I'll just multiply ForceToAdd with Time.deltaTime
wrong vid
fuck
how tf does this make sense
sometimes it launches me over the entire map, other times it barely knocks me an inch
Vector3 knockbackDirection = transform.position - enemy.transform.position;
knockbackDirection.y = 0;
movement.AddForce(knockbackDirection, knockBackForce);```
You're not normalizing your knockbackDirection, that's one thing you need to do
I do inside of this function:
public void AddForce(Vector3 direction, float force){
forceToAdd += direction.normalized * force;
}```
Ah, alright
void ControllerMove(){
forceToAdd = Vector3.Lerp(forceToAdd, Vector3.zero, Mathf.Pow(forceFraction, 100 * Time.deltaTime));
controller.Move(forceToAdd * Time.deltaTime);
}```
and this is the function handling the movement
Then debug it and check the values being passed to AddForce first
Either the force somehow changes, or AddForce is being called multiple times, or your lerping is wrong
Block only got called once so AddForce only gets called once
idk if the normalization is correct tho
it happened there
Then debug how your forceToAdd changes over time
yea it still adds random forces
I mean
its not 100% random
it is more or less the same magnitude
it is 100
I don't know the expected force exactly, but there should be 0 difference between 2 initial knockback forces
so if I knock myself back twice, their magnitude should always be the same
Then debug exactly that
Check the values where the knockback seems alright
What's the direction, force and resulting forceToAdd magnitude
And how it changes over time
Same thing when the knockback is too big, check everything and find out which part of the code causes this behaviour
okay I think I found a fix
I started using fixedDeltaTime in my wrong lerp
which seems to produce the same magnitude every time
hey can i get some help
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
i'm trying to recreate this mechinic in unity
the dash and slash
how can i make this mechinic
in unity
bro i googled i cant find anything about it
theres really a ton of different steps here. all depends how you want it to look and feel. No one will be able to give you an exact answer here on how to do it
The first part already depends on how you're moving the player.
i have the movement code do you want to see it
break the problem down also, you have a dash and slash, this is 2 different problems. The dash depends on how you're moving. The slash is gonna be some vfx and like a physics query to get enemies within the area
so how so i make the dash daigonal
i have some code to relate to it but it doesn't work
Transform [] listOfDashableObjects; // Find list of dashable objects
void Update() {
if (inAir) {
// Get the closest dashable object
Transform closest = null;
float distance = Mathf.Infinity;
foreach(var obj in listOfDashableObjects) {
float dist = Vector3.Distance(transform.position, obj.position);
if (dist < distance /** TODO: Add a max distance check here */) {
closest = obj;
distance = dist;
}
}
// if the user presses dash
if (closest != null && Input.GetDown("dash")) {
Dash(); // Add a force at that direction
}
}
}
💡 💡
👨 | |
void DashTowards(Transform target) {
Vector2 direction = new Vector2(0.5f, 0.5f); // 45deg up to the right
// If the target is to the left of us, lets flip the dash direction around
if (target.x < transform.x) {
direction.x *= -1;
}
// If the target is below, go down
if (target.y < transform.y) {
direction.y *= -1;
}
rigidbody.AddFroce(direction * dashForce);
}
your !IDE probably isnt configured. this is full of errors
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 dont thin thats the problem my ide is not configured
also here is the player movement code
well you've cleared not looked at the #854851968446365696 . having a configured IDE is required for help here
also the readme tells you how to send code
And I've shown you the link for how to configure your IDE so you can solve your errors. How do you expect to solve your errors if your IDE isnt even telling you what's wrong?
i know my bad not your fualt
Is there a tutorial anyone can recommend on timing in Unity?
I just cant find anything that really fits my needs regarding this topic, what im trying to do is for example:
gameObject.SetActive(false);
(Now wait for 5 or so seconds)
gameObject.SetActive(true);
How can i do something like this without using a timer variable or new Method all the time?
Look into coroutines
https://docs.unity3d.com/Manual/Coroutines.html
hello, I have a question regarding sprite arrays
currently made a little dialogue system with text and audio, but now I want to add 2 character portraits. I created a Sprite[] array called images and put 4 images into it. Theres a function called NextLine() and I want the image to switch every time thats played, but ive been stuck on it for 3 hours now. Any ideas?
how can i reference the child of an object i want to instantiate (that doesnt exist previously in the scene) via code?
Does the value of index here also align with what image should be on? Because if so you could just reuse that variable and access your array[index] and assign that to whatever image you need.
Store a reference to it on the parent object is the usual way
this is the index for voicelines, I have yet to add the index for images
I can see that, which is why I ask if that value would be the same for images. You can reuse it if so
I think its reusable
could you elaborate? so am i gonna do and tell what my idea is because maybe there is a better way, i want to instantiate a gameobject thats a section of a infinite runner, so i choose a random one from a list and instantiate it, and now for adjusting a value to the y y came up with this idea right here
It means to put a script on the parent object that references the child object you need. Whatever instantiates the whole prefab can just read it from the parent object.
the green points are start point and the red ones are endpoints, so now i just try to allign the start point to the last current endpoint
maybe its a bad way of doing it but thats the only way i thought that could work
I also have absolutely no clue what you're showing here or what that has to do in relation of grabbing a child object. It seems like you're talking about a new problem
makes sense
the start and end point are 2 gameobjects (the ones i need a reference to so i can get their y value)
but yeah your solution works
Sir, why my codeium won't shows up on my left panel as it used to be @swift crag
this is my first week with codeium
previously I just block the whole code and ask to analyze
I need to link a .uss stylesheet to my UXML, but I cannot see anywhere I can add it to be my visualelement.. ?
There is no + or anywhere I can drop my .uss it is only under data source I can do that, but that seems to be wrong, especially 'cause there is a place for stylesheets
I also just did the one where I click the + here:
But that also seems to be wrong, since it is not connected to the visual element then.
you liking it?
um yeah loved it, but I think the add on starts to dissappear
but it's installed still
coz previously I just allowed to block my whole code and right click for analyze
now the tool was missing
i usually never use the left panel.. but it should be there if the extension is enabled
can someone here help me make a hunger system for the unity 3D game kit
are you paying?
j/k its pretty simple..
the logic is a variable being lerped or movetowards 0 in update
then u have a function to add back X amount
once empty or < 0 = ded
if you have a coding issue or error, it's best to post the relevant code, any errors, and where the problem lies . . .
decrease (subtract) the hunger variable over time. when something is consumed, increase (add) to its value . . .
the thing is
i downloaded a hunger and thirst pack
and i cant get it to work
my original setup had a script named playerontroller
so does the hunger and thirst pack
so like
their clashing
Then you have to fix them manually
is there a way tospeed up compilation of code i have a good midrange PC but it feels like so laggy for making smallest changes to code
Is there a way to start coroutine an IEnumirator method inside an IEnumirator method? because everytime I do this its method just doesnt start
"Is there a way to start an IEnumerator inside an another IEnumerator?"
Is this what you mean?
it's the same way you started the first coroutine . . .
ye but it just doesnt work
Show the code
this doesn't allow us to help you. give the proper information when you !ask a question . . .
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
The syntax is correct
can you override a class?
like u do with methods
i want a base class and add to it
or would inheretance be better
that's what inheritance is for
right
you can only inherit from one class at a time
and an "attachment manager" should not inherit from "attachment". at most it would reference the attachments
yes i know
im just seeing if it even works
i have the whole attachment system finished
is just im rewriting it
Explain what exactly doesn't work
the TypeDialogue method liiterly just doesnt start
Please, show it
You cannot inherit from multiple classes. You can inherit from multiple interfaces and a single class
don't modify the string for typewriter style dialogue, instead assign the entire string then modify the maxVisibleCharacters property
but if that coroutine isn't being started, then the one you are starting it from is also likely not being started
how do I use the maxVisibleCharacters property?
the same way you use any other property
why are the numbers disappear ?
looks like your color has no alpha
alpha ?
transparency
that's the A in RGBA
Maybe show the script that's changing the color
its still doenst start
I think the method just doesnt start
using maxVisibleCharacters has nothing at all to do with starting the coroutine.
i already told you what is likely not causing it to start
the PlayerTurn method does start
prove it
if it wouldn't I litterly couldn't play
and i would be softlocked
the colors in your Damage Color Parameters have no alpha
but I can play, the dialogue just doesnt sturt
you have not shown any code that proves this so i am inclined to not believe it
and when I change the player Turn to void the TypeDialogue does start
see when u have red enabled..
guess what that means? you aren't actually starting the coroutine correctly
the black bar underneath it indicates it has a value of 0 on the alpha..
it should be white
you right ty
but what in code makes it do it ?
it's not the code. it's the colors assigned in the inspector like i've already pointed out
the colors that u have assigned in this script
ohh isee the health controller
thats a silly question. as the other script has nothing to do w/ colors at all
you right my bad
correct.. since u have them serialized just fix them in the inspector
and ty
np 👍 🍀
this doesn't really seem like a good application of generics tbh
trust me for my case it is
how
because i need the base class
which is AvailableAttachments
and then use that
but for different things
like if i need to add a new attachment
i just write it in there
instead of like 5 classes at the same time
that does not explain how generics are useful here.
by not repeating the same code 20 million times
dont worry
because it works as it should
and saves me writing the same shit over 20 times
instead using a base class
and how exactly would you be repeating the same code "20 million times" by just using some base class that your attachments share as the variable type in that AvailableAttachments class?
which i can pass different classes into
u see how i had two different classes?
Why not to make base Attachment class and put code there instead of 20milion places
and they had the same thing
which is sight light and muzzle
if i wanted to add a new attachment type
i'd have to go to each script
and add it manually
yeah, that's just called "bad design", not exactly a usecase for generics
You don't xD just make new class deriving from Attachment base
its called every project is different
alright, well when your code ends up being confusing spaghetti because you barely understand what you are doing and using a tool that is not right for the job you are using it for, don't come crying here
sure
There are just too many classes
no because one holds information for the holder item
which is visible to the player
and one is the world item
which is picked up
its two different things
which u cannot put together
one hold specific information to itself and the other as well
u cant just put this together in one code
one class
this has to work with my inventory system
and as you know every system is different
every system has a different design
my house is different than urs
Supposedly, you mean the item, which exists in the world as a GameObject and its image as a slot?
i cba
finish a thought before pressing enter.
and this phrase right here is a good indicator that perhaps generics are not the right tool for this. generics are good for when multiple systems are similar not different. hence the name "generic"
they are simmilar
i was talking about the inventory system
Yes, but I wouldn't go around saying that if I lived in a house, whose roof collapses when it rains
thats my point
so your point is that it has to be similar but also that your systems are all different so it isn't similar.
What you need is class ItemData, class ItemController : MonoBehaviour and class ItemSlot : MonoBehaviour
i am doing that
i know how inheritence works
and im telling you i cant use it for my attachment system
What is you attachment system used for?
each item that has the AttachableAddon
can hold its own attachments
so if you attach a scope to an ak
it will hold that scope item inside that ak item
so next time you pick it up it will still be there
and then you have to actually enable the model on the ak model
if the specific ak your holding has a scope
A scope attached to the ak is supposed to be ak-specific, isn't it?
yes
to that specific item
because u can craft many aks
so that specific ak has to hold its own attachments
which is what im currently doing
So you can have a class, derived from item, to have a field for scope?
I just have a component on each gun part that has a list of "plugs" and "sockets" which define what part types can be attached and where
is this error coding related? idk what is this
Is it affecting anything, It might be an internal error, not your own code
nope
its usually fine to ignore it then, re-open the project
I have no idea what is going on it just seems that VS doesnt like unity anymore
right click it and try Reload With Dependencies or Regen project files in External Tools of unity
that fixed the first one but not the second one
nvm fixed both now
Hey I'm making a top-down tank game in Unity 3D and does anyone have any good tips for making an enemy AI tank? I can use the navmesh system to make it move around and stuff but I am having trouble getting it to actually move like a tank
in what way ?
thats pretty neat
although i would do a check for the AI tank to only shoot if the barrel is under a certain threshold of looking at the player
wdym too much angle now?
no if you look in the gif, when you go behind the wall and come out the AI tank shoots even when its not looking at you, well so yes the gun has to much angle before shooting target 😅
well mostly when it gets a point on the navmesh to move to it will turn as it moves to the point which is not something a tank could do, so my current solution is to have it stop and turn to face the point before moving towards it. if youve ever played a video game with tank controls its like that. the problem with that is that while its turning it makes it a very easy target to shoot, so i'd prefer for it to have a turning arc, so it keeps moving while also turning towards the point on the navmesh. i made a video showcasing the 2 turning styles with the player tank that im controlling
oh yeah should fix that lol I havent touched this project since last year
a tank could do that
you would need to show us code for what you have now, a tank can do both turning in place then moving and turning while moving
i know it can do turning in place that problem with that is that it just makes it a very easy target to shoot at
hmm you could grab the generated navpoints then smooth them out and pass those final points manually moving it, I wouldn't know how you'd make it an arch instead though.
show us your code of what you have
I do have some code that I was working on in order to get it to turn in more of an arc, the problem is that it messes with the navmesh so it keeps getting stuck on walls
!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 want it to arch i would just get the next position of the navmesh and move and rotate manually there
i would also keep the turning in place for if the agent gets confused
https://beta.myst.rs/r6pq1mnu the looking around is not smooth at all idk why
yeah right now I'm currently working on the HandleStuck part in my code so that it could turn around if it gets stuck on a wall
yeah for sure, the arch would be great to look at but when the agent gets stuck or is confused you should have the turn in place, if it is getting stuck in walls then you should teleport the agent to the closest point outside of a wall, preferably the previous position
how would i make it so the forces are constantly being applied till they make conatct then switch
set a bool to true on enter
and in Update you can apply the force if the bool is true
If I am making a android game what should be the save speed is ms for my game to save data consistently onApplocationQuit or any another function
i tried thsi but i crashed unity lol
huh
it completelyfroze
You don’t need two bools for that, plus the up() and down() must be on update under an if with the bool
just do if(goingUp) Up(); in Update
And else Down(); assuming this is like Gravity Guy
Plus you could do this with only an if without making two functions
Unity will wait for all your scripts to have finished executing before it proceeds on rendering the next frame. If one of your scripts doesn't finish (eg. with an infinite loop), you'll freeze it.
Remember that when your code runs, nothing else runs (except for multithreaded code - coroutines aren't a part of that)
hi, im trying to clamp where the player can rotate the inventory to by the amount of objects but im not sure how i would go about doing it, i had a try with mathf.clamp but that didnt work, is there something i can do to reference if the index of the item list is at the start or end maybe?
input method - https://gdl.space/ewuhuweyoz.cs
Change both conditions to "if up/down arrow AND that I'm not already at the beginning/end of the inventory"
You need a variable to track what the current index you're at in the inventory
yeah i do i probably shouldve included that
ill see about this
what does this small plus icon next to the box mean
the change isnt updated to the prefab
in the inspector of the parent next to the name theres a button
you can do it there
"overrides"
to do that last part im assuming im comparing the index of the current item to the start and end indexes of the inventory?
Yep
great cheers
i think i saw it being a button itself before, maybe depends on the Unity version not sure
but for you its overrides
oh shit it worked thanks alot
Yeah means the children objects were added, compared to the prefab
also for some reason i cant drag the thirst text into the text area in the script in the inspector of the parent
its probably a text mesh pro
If you're using TextMeshPro, the type to use in the code is TMP_Text instead of Text
yu
yup
it is
is there a way to make it normal text
no, use TMP
Prefer TMP, it's better
change the variable type like SPR2 said
oh
Plus for simple operations it's used the same in the code, you won't have to change much
so i just edit the script and put TMP instead of text
TMP_Text instead of Text
hey guys, when i try to log into unity I need a code and i enter it and i get “Invalid code”
and you would need using TMPro; instead of unityengine.ui
got it
If you're not programming this feature yourself, ask in #💻┃unity-talk for general help
oh ok
ended up going with this
im getting the same issue guys
Hello, my start method isn't running on my prefab when instaitiated
{
gameManager = Game_Manager.Instance;
if (gameManager == null)
{
Debug.LogError("Game_Manager instance is null in QuestSlot.");
return;
}
questManager = gameManager.questManager;
if (questManager == null)
{
Debug.LogError("questManager is null in Game_Manager.");
return;
}
questSystemUI = questManager.questSystemUI;
if (questSystemUI == null)
{
Debug.LogError("questSystemUI is null in QuestManager.");
return;
}
Debug.Log("QuestSlot Start");
Debug.Log(questManager == null ? "questManager is null" : "questManager is not null");
}```
Any idea why?
The prefab is made during runtime. I get no Debug logs from this, but I do from my Game Manager and stuff.
Make sure the prefab has the script, that it is enabled (the check box aside its name in the Inspector is checked), and that the object the script is on is active (check box at the top of the Inspector is checked)
it does
If you added the script to an instance of the prefab (for example in the scene), make sure to Apply the changes to the prefab itself
prefab is the same, like, If I add more debugging to the void start method it will work, its so confusing
it makes no sense ot me
Do you get any exceptions logged in the Console? Make sure errors are not filtered out
heres the scipt that i edited still cant put tmp in the text area
Also put a log, but at the beginning of Start
To change the text, the property to use is still .text.
You need to configure your !ide before proceeding any further.
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
already done
No exception or warnings, just my debug logs from other scripts.
I figured it out and it was dumb
dont wanna talk about it
It's not, lines 25 and 31 should be underlined red, the issues are here.
Having a configured editor is required to get help here
without fixing your config you will get no help here
oh
how to save variable when creating prefab but not save variable when instantiating
done
switched to microsoft visual
Good choice
So for a reason i really cannot figure out, my OnTriggerEnter2D does not work anymore all of the sudden.
It worked fine before i added the if (shipDead == true) and IEnumerator ShipDeath.
Why is this?
void Update()
{
if (ship_hp == 0 || ship_hp <= 0)
{
shipDead = true;
}
if (shipDead == true)
{
StartCoroutine(ShipDeath());
shipDead = false;
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Bullet")
{
Destroy(other.gameObject);
ship_hp -= 1;
AS.PlayOneShot(hit);
}
}
IEnumerator ShipDeath()
{
AS.PlayOneShot(explosion);
Color color = Color.red;
yield return new WaitForSeconds(1);
Instantiate(Particles, transform.position, Quaternion.identity);
yield return new WaitForSeconds(5);
gameObject.SetActive(false);
DestroyImmediate(Particles, true);
yield return null;
StopAllCoroutines();
}
}
}
so can i get the help 😄
Yes, refer to my comment a bit before
yea so how do i change the property
With your keyboard
... 💀
ohhh
because it is INSIDE your Update method
Oh, so certain functions do not work when inside the Update method? Do they have to be on their own to work properly?
can i mark variable as non copyable on instantiate
yes, never nest methods unless you have a good reason to do so
Thanks alot
they reside outside of the update method
i appreciate it
When they're inside, Unity cannot see them, so it cannot execute them
LESS GOO IT WORKED I LOVE THIS SERVER
Yes
IS rotation Frame dependant or not my left and right roation on mouse feels so laggy and idk whyand its driving me insane
do not cross post
didnt mean to just putting it in a better place and also glad someone seen and yet still didnt answer the question :3
Depends on your code.
https://beta.myst.rs/r6pq1mnu - fps controller
https://beta.myst.rs/2s9aiepg - input manager
you know why I didn't answer? Because I looked at the code you posted and saw absolutely no effort to try to debug it
i mean i did try ive been trying for 3 hours trying different methods of rotation looking through the docs to no help at all
setting the .rotation manually? using .rotation is not framerate dependent but Update() is.
then why isn't your code peppered with Debug.Logs?
but your inputs counteract this, unless they are multiplied by Time.Deltatime which makes buggy movements, since inputs already do this
how is that going to help me with how smooth the rotation is
because it shows you exaxctly what is happening and what values you are using. Debugging 101
ive tried using time.deltatime in multiple places just doesnt help at all just makes the rotation not happen pretty much at all
hi, handle rotation in lateupdate, it will solve all of your issues.
You should do camera rotation in LateUpdate, not Update
unless they are multiplied by
Time.Deltatimewhich makes buggy movements, since inputs already do this
dont useTime.deltatimefor inputs
oh i misread your message mb
Thank you both it feels a lot smoother now @verbal dome
hello guys, i have this script that controlls the location of the object , but i want to reference it to a controll those parameters in the shader how do i reference it?
the script was made by chatgpt , 😊 just want to controll couple of parameters with the script
Look at the reference name of the parameter in the shader graph. Then once you have that, get the material from the code, and use the appropriate Set method on it, to change these parameters. SetFloat() would correspond to float inputs
thanks!
For some reason This loop never starts:
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
(this is just a small part of the code)
i > 2 should be i < 2
thank you!
is there any way to change the tree render distance?
Hey all,
I'm working on a Vehicle Enter/Exit script and am trying to get the players 'pose' to change using Unity's built in IK solution.
The IK works perfectly 'outside' of the vehicle, but I'm having a weird issue when 'sitting' in the seat.
https://hastebin.com/share/anirakigeg.csharp
I have some 'target objects' attached to the vehicle seat (the idea is that I want to use the same script for multiple vehicles).
I used these 'target objects' as target positions for the IK target object positions (enter the vehicle, hands/legs/spine ik controllers move to the 'target' objects positions. Now, this does actually work (see image), the red Boxes are all in the correct positions.
The issue I'm having is that none of the character bones are moving to them as they should. The controllers still work (I can move them around and the arms/leg bones move, but from where they are in the image.
Can anyone see the issue? Been trying to figure it out for most of the day 😕
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
why would u want to have a void in a void
fyi they are called methods not voids
i call them voids my bad
idk never heard someone say method
void is the return type, indicating that the method does not return any value
basically everyone here calls them a method or a function
void is a return type. what would you call
int Mymethod() {}
Method is the official name
nice
it's even in the message you replied to
my bad
oh yeah function yeah
Does anybody know the encryption method for .dat save files for mobile unity games?
it can be absolutely anything implemented by the developers
Okay I'm looking at the game pewdiepie Tuber simulator in particular
so ask the developers, they are the only ones that can tell you
There's a apk that unexrypts them for the game but the problem is that it was made for a older version of android that looks into that android data folder which does not work anymore
Decompilation/modding/reverse engineering of third party games is not something we offer help with here.
we do not discuss these things on this server
Okay
using System.Collections.Generic;
using UnityEngine;
public class ProjectileLogic : MonoBehaviour {
public int speed;
public GameObject target;
public string projectileType;
void Update() {
if (target != null) {
Vector3 direction = (target.transform.position - transform.position).normalized;
transform.position += direction * speed * Time.deltaTime;
Quaternion lookRotation = Quaternion.LookRotation(direction);
transform.rotation = lookRotation;
}
}
void OnCollisionEnter(Collision collision) {
if (collision.gameObject == target) {
EnemyInitiate enemyInitiate = target.GetComponent<EnemyInitiate>();
if (enemyInitiate != null) {
enemyInitiate.health -= 20;
Destroy(gameObject);
}
}
}
}```
This ^ is the only code controlling the projectile's movement, and it's only telling it to go towards the target, yet it is equally drawn to the top left of the game towards literally nothing and I can't figure out why. Here's the instantiation code:
```void StartProjectile(int targetID) {
GameObject target = GameObject.Find("Enemy_" + targetID);
if (target != null) {
GameObject newProjectile = Instantiate(cannonProjectile, transform.position, Quaternion.identity);
ProjectileLogic projectileLogic = newProjectile.GetComponent<ProjectileLogic>();
if (projectileLogic != null) {
projectileLogic.target = target;
}
else {
Debug.Log("Projectile logic script could not be found in cannon projectile.");
}
}
}```
Any help is greatly appreciated.
Your projectile has a Rigidbody, yet you move it from the Transform directly. This bypasses the physics engine and might lead to weird results
I see, thank you. The issue with removing it is that the collision won't be detected when it hits an enemy, but I can just make it apply the damage once its within a certain range of the enemy rather than colliding if there's no easy workaround.
You could use the Rigidbody to move it, using the MovePosition() or AddForce() methods
Well on second thought, can it pass through objects that are not the one its targeting? If not the alternative might be the way to go
the rigidbody obeys the physics system, so it will detect collisions
using the transform doesnt, i would just use the built in rigidbody functions
Is there a way to make it so that an IEnumerator method "locks" itself so it cannot be called again until the code is finished or yield breaked?
Yes, set a variable to true when you call it and set it to false at the end of the coroutine
And only call it while the variable is false
It will stop at any collider in its path, unless you modify the physics settings to tell it that the layer "projectile" does not collide with any other layer except whatever layer the enemy is on
So what do you think I should do
Just make it destroy and damage when its within say 1 distance from the target?
I don't need it to have physics
Just go towards the target
Do you want realistic (bullet velocity, bullet drop) physics?
I do not
Making it like COC
But going over it has made the answer pretty obvious
Thank you :)
You could make a script that raycasts from the last position of the projectile to the current position, and check that the colliders detected in between contains your enemy
i would use the rigidbody to detect collisions and use the functions, using translation and detecting collisions yourself every frame by using Overlapsphere or checking the distance is slower than just using the rigidbodies built in collision detection
Hello, not sure whether this belongs in code-general but I am trying to make make script spawn in a turret and then set it to TurretList. All the turret prefabs have the turret tag and yet instead of being set on line 79 to feature the three turrets, on line 80 it tells me that turret list is 0 keys long. Does anyone know why this is happening? thanks! (The "GenerateTurret" code is hashed out on lines 75-76)
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Is there a way to dissable a function so it doesent react anymore? Like OnTriggerEnter doesnt react to any Triggers any longer?
Set a boolean on it and as the first line of that function do if (thatBool) return;
OnTriggerEnter specifically works on disabled objects because it's often used to "wake up" disabled scripts when the player is near them
On a diffrent note, when dissabling scripts, is there a status that an object can be in which dissables all interactions and codes? Like gameObject.SetActive() but without the object actually dissaperaring?
When you destroy a unity object but keep a reference around you can still access it but you get errors when you do.
Officially there is no such state.
Okay one last thing i wanted to ask today
Theese operators are kind of messing up my code. How do i devide the Operators so they work on their own instead of combining each other?
Which means i want to make it that the if() statement returns true if:
(ship_hp = 0) + (OR ship_hp <= 0) + (AND shootable == true)
not if:
(ship_hp = 0) + (OR ship_hp <= 0 AND shootable == true)
I really hope this is not too confusing to ask for i really dont know how to word it.
Do i use commas? Or anything else?
AND binds stronger than OR, use brackets to organize your statements. A comma in a paper math statement is an AND
Thanks, tho
How do i put them to seperate the operators?
Maybe read up on c# expression syntax
Just saying those 2 checks on the hp are overlapping. You are checking ( if it's equal to 0) or (less than or equal to 0)
This is great, i was wondering how you call those. Thank you!
This is the complete source of truth, but it has way more info than you need https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions
yeah ik that was my problem here i couldnt figure out
I'm not sure if you understood what I meant, the statement that you said you want to check for has a redundant check. Meaning you dont need to check if its 0 and also check if it's less or equal to 0
Ah i get it now. Was confusing since english isnt my first language. So youre saying i can leave out the ship_hp == 0?
Yes
Thats really helpful to know so my code wont be so messy, thanks man!
I NEED he l p
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
the debug Path runs, but OVC and i does not, im not sure why 🤔
if(pathfinding)
{
Debug.Log("Path");
while(true){
Collider[] OVC = Physics.OverlapSphere(currentnode.position, AISphereRadius, WPtransformmask);
Debug.Log("OVC");
for (int i = 0; i < OVC.Length; i++){
Debug.Log("i");
Openednode.Add(OVC[i].transform);
float OpenStartCost = Vector3.Distance(OVC[i].transform.position, Startpoint.position);
float OpenEndCost = Vector3.Distance(OVC[i].transform.position, Endpoint.position);
int OpenIntStart = (int)OpenStartCost;
int OpenIntEnd = (int)OpenEndCost;
int OpenFinalCost = OpenIntStart + OpenIntEnd;
if(FinalCost < distmin && Openednode.Contains(OVC[i].transform)){
currentnode = OVC[i].transform;
Openednode.Remove(currentnode);
Closednode.Add(currentnode);
}
}
}
A runtime error perhaps?
all im seeing in console is the debug path and my try-catch to tell me if a point exists, and my script is running to so im a little confuzzled
What try catch? Where? It could be catching the error for you.
If an error is thrown, the code execution stops. It doesn't matter if you catch the error later on.
it may have been catching the error, I think i had an infinite loop in there on accident so my unity is most likely gonna crash 😅
PLZZZ
please what
help me make first person game
Stop. Read #854851968446365696 on how to ask questions and how not to.
stop being rude plez
<@&502884371011731486>
No one is gonna make a game for you here. The best we can do is answer a specific question.
make it yourself
why are u mentioning a mod
@alpine cairn This isn't the place to spam for people to make games for you. This is a learning server.
im not spamming
@alpine cairn you might get muted or even worse banned if you keep it up
You are repeatedly posting "plzzz", which is unecessary spamming
Oh sorry I didnt see a mod was already typing.
Yes, you are. If you want to collaborate with people, use the Discussions site. !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
help on what?
So ask a specific question.
speak up
need
Nope. Post a complete sentence.
!mute 1268096070488166451 3d Return when you can actually ask a question.
zen_gull_53076 was muted.
my playmode is busy for 4 minutes 😂
If it is an infinite loop, you might be able to pause in VS if the debugger is attached. Otherwise you'd have to just close unity
I've seen others say sometimes you can attach the debugger during it and pause but I've never gotten it myself to work lol
ah rip, i didnt have the debugger on
They could attach it to process
i just closed unity but it didnt close and everything seems fine? im not even gonna question it
do you need to yield for while(true) or else it will hang unity?
Unless you break from it in a reasonable amount of time, yes.
It would hang any program, not just unity.
alrighty then that was my issue, thanks 👍
Btw, yield would only apply to a coroutine.
In any other case, you need to break out of the loop
can anyone help me with this error i cant find or fix with photon's pun2? the error: Got DisconnectMessage. Code: 104 Msg: "InvalidEventCode". Debug Info: {}. the script I believe is causing this is:
Networking is really not a beginner topic and there's a channel for that: #archived-networking
oh ok
Is there a function that will play when the script ends?
Wdym by "the script ends"?
i have a another script that turns on and off the game object. When it turns off the game object the script associated will also stop. I want it to run a code when the script associated with the game object stops.
So, when it's disabled. There's an OnDisable method that would be called.
ok thanks
Hi, I'm not sure if this is the best chat to ask but had anyone experienced transform handle offsets that don't align with the actual position and rotation? I have a joint hierarchy for the character and none of the joints are represented correctly. Furthermore trying to rotate the joint rotates it around this phantom handle axis instead of where it's actually located. I know where it's actually located since visually all the meshes are in the right place and rotation + draw gizmo pins the positions correctly, just the handles are off
Switch your tool handle position to Pivot
Right now you likely have it on Center
Anyone else get into a situation, where you feel like you can do something better in your programming, but can't quite think of it?
Like, you can get something to work, but the code is kinda weird
I'm new to Unity so I don't have the most experience with cameras, so I decided to look at cinemachine since some tutorials were using it. They used Camera.main to assign the Object to a variable, but when I do that it is null.
I do have the tag as MainCamera for the cinemachine virtual camera object. Everything I can find online says that's the issue but nothing else.
Someone hepl this is extremely frustrating. I spent the entire weekend on this rpoject and I can't build it. The thing keeps saying UI doesn't exist in the namespace unity. wtf do I do I've literlaly tried everything, reinstalling the editor reinstalling the 2D package and the UI package and trhe textmeshpro packacge deleitng the librarby folder deleting all the visual studio folders reinstalling the visual studio package
this is just experience. im sure this can be said about most peoples beginning attempts for player movement scripts.
the MainCamera tag should be on the object with the unity camera
That's fair. Considering most of the territory I'm dealing with right now is brand new to me, it could easily be compared to when I started doing player movement.
You'd have to show your code, your scene, and the error.
It doesn't sound like it has anything to do with Cinemachine though
Might want to share the actual errors and their details.
In godot, you can connect a collider signal to a script in another object.
In Unity, a Box Collider calls OnTriggerEnter when something enters the area. Is there a way to connect this function call to another script, or do I have to always add a script to this Box Collider/GameObject if I want to do that/and for every functionality?
You can easily make a script that has a UnityEvent that gets triggered in OnTriggerEnter. Then you can subscribe whatever you'd like to the UnityEvent
Is there any way one single gameobject can listen to multiple objects by itself, or do these multiple objects always have to subscribe that one single gameobject first?
depends on your hierarchy. If you have a parent with a rigidbody and children with colliders then the parent can receive the collisions on the children
i see, the parent isnt a rigidbody, its just a GameObject. I'm doing things with areas in a prefab hallway that a player walks into, and the level will change and add prefabbed hallways depending on the area that the player walks into.
Since the hallways will be generated in runtime i thought it would be easier to have one single manager script listening to those box collider areas rather than having to code multiple box colliders subscribing to one script
Hey yall, not sure if this kind of question fits here or not so I apologize if it doesnt, I have decided to start learning unity as I was always interested in game dev. Someone told me that I should learn the C# basics, as in loops, classes and functions mostly. Are those enough to start tinkering around in unity? If yes, do I just look up a random tutorial and go off of that?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Mornin' all.
I'm having a bit of a weird issue that I can't for the life of me see where the problem is. I've got a simple 'enter/exit vehicle' script that works almost perfectly.
https://hastebin.com/share/ozetovafoz.csharp
This gets called by an 'interaction' script on the player.
https://hastebin.com/share/ifowokarux.csharp
The issue is that the first time I try to interact to 'drive' the vehicle(s), the switch script behaves as if I am already 'driving' the vehicle (as if the bool isDriving is set to True), and I'm a little confused as to why.
Can anyone see where my error is please?
Video for reference.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
if you have a decent understanding of those concepts, plus how to actually write some lines of code yourself, then yea thats a better starting point than a lot of beginners here. the learn site steve linked will teach you unity basics
Did you log your isDriving boolean when entering? Maybe you are setting it in inspector or something gets triggered twice?
Thanks for the answers, yeah, I have the concepts already since I programmed in other languages, should I just keep following unity learn until I feel comfortable with smaller projects then learn whatever I need in smaller bits?
The logs in the console are the boolean (the warnings are something unrelated and non-game breaking so ignore those.
only those 2 Enter and Exit is changing isDriving ?
Yeah.
hi, im a beginner in unity and am currently trying to make a basic crossy road esque game to learn stuff. So basically I want the game over screen to pop up whenver my chicken collides with a car. Both game objects have colliders and the chicken has a kinematic rigid body too. The car is tagged correctly and I don't think theres a problem with layers. But the OnCollisionEnter2D still doesnt execute. Can anybody help me with why?
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.transform.tag == "Car")
{
Debug.Log("Game over");
gameOverScreen.SetActive(true);
chickenIsAlive = false;
}
}
}```
have you used java before? c# is basically the same. if so, yea u could just keep going on unity learn or make your own small project if you have an idea. Really the tutorials should just be there to tell you what exists in unity, and roughly what its used for. If you understand coding well, you'll quickly see that most tutorials really are bad. for example, the unity docs is purely just to show you how to use the functions. a lot of the time the code itself is questionable. Not sure about unity learn as ive done like 2 lessons on it.
The same goes for youtube tutorials. Most are really bad when you look closely. But you can always use them to get an idea of what exists or how something can roughly be done
Those logs should happen once, not multiple times, right?
he put it in update, and isdriving is false when he is on bike
to start with, debug if the method even runs and what the collision objects tag is
Ive mostly used python and im aware of the fact that most tutorials are bad since they usually just tell you the answers with small explanations
That was my bad tbh. I had the logs running in update. Gimme a sec.
So you should make sure, that the interaction is happening once before accepting a new state.
the tag is Car but no the collision snippet isnt running. I dont see the debug statement in the console
so do as I suggest. You KNOW nothing until you do you are just assuming atm
Also, where do you trigger EnterVehicle()? I cant see it in your scripts or am I blind 😄
okay how exactly do i go about this?
Add a Debug.Log before the if outputing the tag
okay i did that and its not showing up in console
so your method is not executing which means your setup is incorrect
I have an 'interaction' script.....
public class Interactable : MonoBehaviour
{
public UnityEvent OnInteract;
public void Interaction()
{
OnInteract.Invoke();
}
}
This triggers the EnterVehicle method
Ah, okay, thanks for clarification
alright so what all should i verify?
You should really learn how to google things and research. Spoonfed developing wont help you learn anything
I am having an issue where editor attributes such as range and editor button are not appearing or having an effect in the toolbox. Is there any setting or whatnot that I have to change?
[SerializeField] [Range(0, 100)]
public float dragCoefficient = 0.1f;
[SerializeField] [Range(0, 1000)]
public float maxSpeed = 100.0f;
[EndGroup]
[EditorButton("ResetMotion", "Reset Motion")]
Put the range attribute in the next line
additionally, private variables are showing up in the toolbox... is there a way to remove this?
no luck
Okay, I threw in some more useful debug.logs. It looks like it's triggering the ExitVehicle Method straight away on the first 'interaction' and I'm really not sure why.
Is the inspector probably driven by a custom editor inspector?
no
Because you are on the one hand triggering the interaction, it gets true and update checks for your input and detects the keydown and exits, I guess
https://docs.unity3d.com/Manual/ExecutionOrder.html physics before input. So I guess, its exeucting the update of the physics script first. Why not just make the interaction check for itself and switch the boolean instead of you mixing up update input and physics raycast at the same time?
I find it weird that it only happens the first time the EnterVehicle() is called though. Weirder thing, I had this working perfectly yesterday. lol.
Phew, you never know what script gets called first until you set the executionorder manually. Thats why I suggest, decide on one interaction input type, not a mixture. Also I suggest switchintg to the new input system
Any screenshot of your inspector?
And what does your current script look like?
[SerializeField]
[Range(0, 100)]
public float ThrustForce = 10.0f;
[SerializeField]
[Range(0, 100)]
public float ManeuverForce = 10.0f;
[SerializeField]
[Range(0, 100)]
public float DragCoefficient = 0.1f;
[SerializeField]
[Range(0, 1000)]
public float MaxSpeed = 100.0f;
you do realize that for public variables you do not need [SerializeField] at all
this is working perfectly fine on my side. even if public values are serialized anyways
trying everything out here man
hi im new to coding
Show the full script. What is your class type?
Also, just remove [SerializeField] for now for the public values
what is the class type
class PlayerController : MonoBehaviour
Did you remove the serializefield and leave only range?
yes
What does Range show you as tooltip when hovering it?
Can you show the top of your class? PlayerController : Monobehaviour etc.? You sure there is no custom editorlayout lying around somewhere?
And did you restart your visual studio/vs code?
what coding app do you guys sugest?
I am using visual studio coming with unity. Personal preference for a lot of cases Id say. Some use rider, some use AI driven stuff and what not
thx
using UnityEngine;
using UnityEngine.InputSystem;
namespace SpaceAsh.Player
{
public class PlayerController : MonoBehaviour
{
# region Inspector Variables
//[BeginGroup("Game Objects")]
public InputActionAsset playerControls;
public Camera playerCamera;
public GameObject ship;
public Rigidbody2D shipRigidbody;
//[EndGroup] [BeginGroup("Movement Variables")]
[Range(0, 100)]
public float thrustForce = 10.0f;
[Range(0, 100)]
public float maneuverForce = 10.0f;
[Range(0, 100)]
public float dragCoefficient = 0.1f;
[Range(0, 1000)]
public float maxSpeed = 100.0f;
//[EndGroup]
//[EditorButton("ResetMotion", "Reset Motion")]
# endregion
/.../
}
}
region? why is there a space to it between hashtag and region?
im in school rn cann u help me write with a walking script when im home?
thats a whitespace
regions allow you to block off code
Please keep personal chats out of this 😄
I know what regions are 😄 Just was wondering, why its not autocorrecting yours to remove whitespace which makes me wonder, if your whole setup is set up correctly
when i get home today can you help me with a walking script??
You can always come here to ask globally. I wont give 1:1 support as noone else here does most of the time, as we are all here on free basis to help eachother 🙂
commented it out nothing changed
ahh its rider, my bad then.
ty for helping when i get home i will se if i can get some help
Okay so. If you add a new public variable, does it show up after saving?
yes
Copy/Pasted your script
Somethings def. broken on your side. no errors or warnings in unity?
there is no setting or anything that may change the behavior of the editor?
no
Are you in debug mode or something?
nope
One more question related to this, what IDE should I use? Previously I mostly used VSC for other languages, is that going to be fine for this as well?
I worked with both, code and studio, both worked well, personal preference for most parts as long as you dont need any special case covered
this a good version to be using?
Did you check this box by any chance? ProjectSettings => Editor
def inspec?
Yep, it should be unchecked, at least its on my editor
Hm, out of ideas then
back to godot I go ig 😭
Just try another editor version and see if things change
I def have a corrupted install
what ver u on?
I am working with unity 6 cause I need some features. So I cant tell you what 2022 version is best
Last one I used was .41f1
There is .48 out, maybe update
im going down to 2021 lts
i was on 2022 .47
Ah okay, because it says 47 on your screenshot
edited.
can someone help i am getting a null ref error at enemy script line 26 when checking for isEnemyArea, which is in player script
the reference variable on that line is null . . .
you never assign a value to playerScript
you need to assign a value to playerScript . . .
playerscript = getcomponent<Playe>()
i di this too but it was same
sorry for typo error but this is assigning right ?
is Player on the same Game Object?
well, does the GameObject this script is attached to have a Player component?
I did a serializedfield and assigned the player object to it
no player and enemy are different game objects with different scripts
so GetComponent on it's own can never work
actually i want to access the bool variable from the player script in enemy script, can u let me know a better way
you have the GameObject player in your script so
playerScript = player.GetComponent<Player>();
would have worked
yeah that was i thinking why is it returning null when i am adding the component
because the component cannot be found on the CURRENT game object
Is there only one player present at all time?
Then you could use the singleton pattern to always have access to your player
the private set and public get thing, i mean instance
Yep, that instance thing
Ok I will try Thanks :), i will try get a solution around it
If you will want OnCollisionXXX to get called in children too, you could use my package: it also aims to send disabled collider messages https://github.com/RiskyWilhelm/UnityColliderSupport
Hi, is there any reason a Debug.Log is being called non stop when the function I call should work only when I click certain button in my app? For instance, I click once a button that calls ChangePhase function and now the debug says "Current Phase is Create List" without non stop, I have checked the script and the Inspector but there are no other ways this should be called so many times. Last week I did not had any problem, is just today that I opened the project and it went crazy
did you check the stack traces to see the call stack?
how do i check?
select the message, the stack trace appears below
Phase is already CreateList. No change needed.
0x00007ff604fdde3d (Unity) StackWalker::GetCurrentCallstack
0x00007ff604fe2f19 (Unity) StackWalker::ShowCallstack
0x00007ff605fd2eb1 (Unity) GetStacktrace
something like this?
just screenshot the console window
And what code are you triggering? Can you share it
so it looks like your menumanager is firing events
public void SetListType(int type)
{
listTypeIndex = type;
for (int i = 0; i < typeListButtons.Length; i++)
typeListButtons[i].interactable = (i != listTypeIndex);
currentListType = (ListType)listTypeIndex;
Debug.Log("Current type of list is " + currentListType);
}
This is called from the buttons on the UI
public void ChangePhase(string text)
{
if (Enum.TryParse(text, out MenuPhase newPhase))
{
if (menuPhase != newPhase)
{
menuPhase = newPhase;
UpdateMenuObjectsWithAnimation();
Debug.Log("Phase changed to: " + menuPhase);
}
else Debug.Log("Phase is already " + newPhase + ". No change needed.");
}
else Debug.LogError("Invalid phase name: " + text);
GeneralInfoText();
Debug.Log("Current phase is: " + menuPhase);
}
This is called from different sources since changing phase happens when I click certains buttons in the app
!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.
At a guess you have multiple subscriptions to the event. Are you using AddListener ?
the only code with addlistener is in Start() in ListManager, to whichi I have set up to check the inputfield and to make the "Create" button available only if there are characters for the list name, but other than this, I have no other listeners
ok, you have your console collapsed, uncollapse it and check the stack traces for the instances of that message. See if there are any differences
what should be looking for again?
it is very clear to see which part of your code is in the call stack calling, eventually, the Debug.Log. So you need to look at the messages you think should not be there and see if they are all being called from the same place
At a very wild guess, looking at this the fault lies in your ListManager. doing too many AddListeners without removing them correctly
well everything was solved as magic when I just restarted Unity, now things work without the console calling the same function countless times
i looked into how to save a game, in stardew valley clone game should i go for BinaryFormatter or JSON ?
it utilized scriptable object for recipe and player can make their own crafting recipe (cooking game). im not sure how to save SO in json
but i read that binary method is unsecure ?, i dont mind if player cheating the save file but i dont want to make it too easy
A scriptable object is just serialized data, you can serialize the data to json and back
Dont use binary formatter. The docs do say, it's not secure. The alternative can be binary writer.
But either way its up to you and the actual serialization of it should be pretty easily swapped out. Meaning you should just call a method to save your data, and in that method you do either your json or binary.
Json will be human readable, binary wont be
Json being human readable also means it's easier for you to see when something goes wrong
i only learned the basic so it will be tedious though, storing that information one by one. i watched binary can store custom class.
welp, better savfe than sorry. json it is
It's not like json cant store custom classes. Basically everything is a custom class
yes as i mentioned i just learned the basic, perhaps there is more technique down the line
Look into Newtonsoft. There is also some plugin that has a bunch of conversions for unity types so you can serialize stuff like vector3
There isnt much to it honestly. If you can save an int, you can save your custom class. It's literally the same code.
Also it's a bit easier when you make classes that contain only the information you want to save.
anyone know why u cant see my player object in the game tab?
Probably due to its z position relative to the camera
This is also not a coding question
There's a better way of doing this, isn't there?
public InputActionAsset inputActions;
public Animator animator;
InputAction move;
InputAction look;
InputAction punch;
InputAction jump;
InputAction crouch;
public bool canMove;
// Start is called before the first frame update
void Start()
{
move = inputActions.FindAction("Move");
look = inputActions.FindAction("Look");
punch = inputActions.FindAction("Punch");
jump = inputActions.FindAction("Jump");
crouch = inputActions.FindAction("Crouch");
}
Serializing InputActionReferences; using the C# generator of the Input Action Asset; or just doing what you've done, as there's nothing really wrong with it.
Anyone know how to make VS always
{
}
instead of doing a normal line break when you press enter in the middle of a {}?
Anyone know why characterController.isGrounded rapidly switches between True and False?
private void FixedUpdate()
{
if (!(characterController.isGrounded))
{
velocity += (Vector3.down * Time.fixedDeltaTime);
}
else if (velocity.y != 0 || velocity.y < 0)
{
velocity.y = 0;
}
velocity = velocity * (characterController.isGrounded ? 0.5f - Time.fixedDeltaTime : 1 - Time.fixedDeltaTime);
Debug.Log($"Velocity: {velocity}, Grounded: {characterController.isGrounded}, movement: {move.ReadValue<Vector2>()}");
characterController.Move(velocity);
}
Probably because you're resetting the y velocity to zero whenever it is grounded resulting in the capsule cast on the CC to not actually go in any direction to detect the ground that frame.
The docs have an example on how to move and jump, use that as a working base.
What API to use for the Database of the Unity Game?
Wdym by "the database"?
What are you trying to do
Like storing completed levels
Why do you need a database for that
Sounds like you're just asking about a saved game system
If it us just “what levels have been completed” I like to use JSON personally
If you specifically want online storage look into firebase or other cloud based storage
If you want to just save player progress on the device:
- Simple data -> PlayerPrefs
- Complicated data -> Json + Filesystem
why does clicking on my object not input anything into the debug log at all, regardless of whether or not i clicked the collider?
do you have an event system in the scene with a Physics2DRaycaster on the camera?
ou sweet, i did have event system but not the raycaster, thank you
Are you doing the physics raycast for testing purposes? It seems redundant
i needed to just make sure it was actually clicking the object, when i click on it i want other things to happen so it does have a purpose
ive got a simple script on a bunch of doors that calculate how close or far the player is, and opens the door when they get close, but the variable isnt syncing with the animator. how can i fix this? do i need to declare the animator component?
where do you set the parameter on the animator?
how would you expect to operate the animator if your script knows nothing about it's existence?
so declare the class and getcomponent in awake?
or declare as a serialized variable and drag the animator component into it
does the avatar part of the animator component matter?
presumably a door does not have an avatar, so no
still got nothin
and are you actually setting the parameter or did you think just referencing the Animator component would magically tell the parameter the value of your completely unrelated variable?
how can i set that then?
did you look at the docs for the animator component?
!docs
I also doing same thing except when i get past the point i make the bool true and if less false, so you can play the animation when close to the point and closing animation when past the point,
there is a codemonkey tutorial also which states this opening and door closing thing that may help 🙂
i got it working, thanks
hi!
I'm trying to manipulate a mesh. for that I want to look at the triangles of the mesh. I would expect triangles to be int[][], an array of 3 integers each which are the indexes of the vertices of the triangle
the triangles array is int[] for me though.. anyone know why this is?
https://docs.unity3d.com/ScriptReference/Mesh.html worth taking a looksie here (specifically https://docs.unity3d.com/ScriptReference/Mesh-triangles.html)
hm, yea.. I would expect Vector3, but it's int[]. why?
triangle is just listing indexes of verticies
yes. it should but it's not. it's just a 1D array of numbers
so a drawn triangle would be:
PSEUDO CODE
mesh.vertecies = [(0, 0, 0); (0, 1, 0); (1, 1, 0)]
mesh.triangles = [0; 1; 2]
the 0, 1, 2 telling that they reference the first, 2nd and 3rd vertex
ah! so it's always pairs of 3?
yes, three connected vertecies that draw a triangle
you know you can easily remap an int[] to a Vector3int[] if it makes it easier for you to work with
adding complexity unnecessarily can cause problems... the most simple solutions usually end up being the best
right..
@astral falcon hi remember me?
you can just use a for loop that increments by 3 every step and go with i, i+1 and i+2 to access the vertecies
I wanna get a good code app but what should I use?
did you just delete a message? looked like syntactic sugar, I'm new to C# and would like to learn things like that
Visual Studio is a free ide, most commonly used for Unity
There are 2 visual stodio code-insider and visual studio code
Yeah I missread what you want to do, it was a linq query to just remap the triangle array to each vertex point, but you want all 3 points of the triangle in a sub array
vs code is pretty decent for me, visual studio is absolutely the easiest if you're not using copilot or something
What do you mean by "2 visual studio code-insider"?
Just imagine some punctuation in the sentence 😄 "There are 2 (,) visual studio code...."
Sorry my English is not the best
Well I think it worked and ima try to. Get a walking script and looking arround
"crocodiles dont swim here"
var mapped = new int[mesh.triangles.Length/3][];
for (var i = 0; i < mesh.triangles.Length; i += 3)
{
mapped[i / 3] = new int[3] { mesh.triangles[i], mesh.triangles[i + 1], mesh.triangles[i + 2] };
}
sorry i had to :c
I'd use tuples or vec3int instead of arrays, for storing individual triangles
Less garbage
Got it. None of them were advised by me. I mean "Visual Studio", and this is the whole application name, without "Code"
where would I seek help for something like the particle system?
Alr thx
if there's two bodies in a collision, collision.impulse will always point toward one body, even if both objects are receiving the OnCollisionEnter message. is there a way i can have the impulse always face the rigidbody on the object that the script is attached to? right now i'm thinking of using dot product to check if the impulse vector is more than 180 degrees away from the vector pointing from the colliding body toward the attached body, and if it is, i'll just multiply it by -1, but i'm wondering if there's a better way
In the installer, select Unity for Unity, .NET for C# without Unity
I think I did it idk
isnt the impulse the combined forces on impact, so if both objects hit each other with the same velocity (reversed) the impulse should be 0
not 100% sure on this tho
I got the wrong one
that's not the issue
the impulse is not pointing at "any" object, it is pointing where the combined forces add up to
impulse is a vector
it points
what you are looking for is the impact position + normal i think
prob have to wait quite long for an answer there right?
impulse is unit force times a change in unit time
force is a vector
therefore impulse is a vector
impulse is the change in force needed to resolve a collision, my issue is that the impulse i'm getting from a collision points in the wrong direction. i.e, if a car hits another car, one of the car's impulses will be pointing in the correct direction, but the other one's impulse will be pointing in the wrong direction
Because you may have semicolons without anything "inside of them"
You can also have as many spaces before putting one, for instance
use "Visual Studio" which comes with Unity. "Visual Studio Code" can be a pain to set up if you aren't already experienced dev
Not sure whether VS Code requires more than selecting it as an ide and downloading a plugin for C#
you could probably ban that in your lint if you really don't like that it can be done
plugin for C#, plugin for Unity, and then fixing the way unity launches VS Code to be able to launch it with line-number properly, not to mention if you've got several unity projects that rely on eachother and want to edit both at the same time from a higher-up codebase in a single editor e.e
I guess that last part is the reason it was a pain for me lol...
If you want to decrease your readability, sure
Sashok so if I wanna code for unity I use c#
that is correct
Alright thank you all so much for helping
Another question (sorry for all the question I'm new to this)
I wanna make a 3d game what should I do for a walking? Mouse looking script
You should !learn through tutorials
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Thats not a coding question but your decision of what you wanna do.
Wdym?
You decide what game you are going to do. There is no best practice for a "3d game". Walking could be anything depending on platform, movement mechanics and what not. But as sidia suggested, first go through the tutorials
Is that in this server?
actually in the link that the bot showed: https://learn.unity.com/
probably just start here: https://learn.unity.com/pathway/unity-essentials
Alight well wish me luck ima start
so.. if I want to sub my mesh into 2 submeshes, I do
this.mesh.subMeshCount = 2;
this.mesh.SetTriangles(someTriangles, 0);
this.mesh.SetTriangles(someOtherTriangles, 1);
MeshRenderer renderer = this.GetComponent<MeshRenderer>();
renderer.materials = new Material[] { someMaterial, someOtherMaterial };
and then I have 2 submeshes with a different material, no?
well i did try and it does not work lol so that's why I'm asking
Yes, you do. You have to select "Unity" in Visual Studio installer if you want to work in Unity. Additionally, you should install ".NET" for C# applications. I would recommend to start from pure C# before going to Unity
Yes, that should be the right solution, what exactly does not work here?
I have half the triangles be one submesh and half the other. only the first submesh is rendered (or visible idk)