#π»βcode-beginner
1 messages Β· Page 229 of 1
yes
using UnityEngine;
public class PlayerAttack : MonoBehaviour
{
[SerializeField] private float attackCooldown;
[SerializeField] private Transform FirePoint;
[SerializeField] private GameObject[] fireballs;
private Animator anim;
private PlayerMovement playerMovement;
private float cooldownTimer = Mathf.Infinity;
private void Awake()
{
anim = GetComponent<Animator>();
playerMovement = GetComponent<PlayerMovement>();
}
private void Update()
{
if (Input.GetMouseButton(0) && cooldownTimer > attackCooldown && playerMovement.canAttack())
Attack();
cooldownTimer += Time.deltaTime;
}
private void Attack()
{
anim.SetTrigger("Attack");
cooldownTimer = 0;
fireballs[FindFireBall()].transform.position = FirePoint.position;
fireballs[FindFireBall()].GetComponent<FireBallscript>().SetDirection(Mathf.Sign(transform.localScale.x));
}
private int FindFireBall()
{
for (int i = 0; i < fireballs.Length; i++)
{
if (!fireballs[i].activeInHierarchy)
return i;
}
return 0;
}
}
Once again, !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.
Format your code properly first.
i don't understand that am i supposed to past my codein one of the links?
Seems pretty self explanatory
Just paste your code in a code block as specified or paste large code blocks on a paste website
okay
I also don't think PlayerAttack is a class relevant to your issue of not being able to jump
Well, he did say that he can't both jump and attack
So where's the part that handles jumping?
But seeing the jumping part of the code would be nice.
there wasn't any issue with jump and attack but just stopped working since i had the issue with hearts
So everything is fixed?
i pasted that in the link wait
how do i share that
paste the link
This is not the code that handles jumping
yes
So is line 58 the part that doesn't work?
yes
First of all, place a debug message in that if-statement to see if it's triggered at all. Also place one at the start of the jump method
See if both of these trigger
yes
You placed the log message where I specified and they both call?
no it doesn't
Neither?
no error oe anything
Alright, so let's see why the method doesn't trigger
My first thought would be wallJumpCooldown
At line 35 there's an if statement that mostly prevents the method from being called. Place a debug message above this statement and log wallJumpCooldown as explained in the link I shared with you
See what the variable value is every frame
yes
Any luck?
Anything specific you get stuck at?
Remember this #π»βcode-beginner message article explains how you can log variables
yes
not really it's just a non expected thing for me i don't really understand i am new to this
but i'll try to figure it out somehow
That's fine, it's not like I expect it to be done perfect. It's a very good skill to learn debugging
Just figure out what wallJumpCooldown is in that method
yes thankyou to both of you for helping me in this
yes i will
Did you manage to do it? The best way would be to put it above the if-statement
yes i am on it
Alright I'll wait for an update
yes
I have another problem
is it okay if i paste the pic here?
i want to delete a transition but it's not giving me an option
in animator window
I want to remove the one in blue
i looked everywhere but it didn't explain anything related to it
Better off asking this one in #πβanimation
it's selected, does hitting the delete key not work?
it's not giving me an option to delete
hit the delete key on your keyboard
AI code
I almost believe you
You've put comments inside ur script explaining exactly what everything is supposed to do, yet you cant figure it out yourself?
And the comments are written with perfect spelling and grammar, but in Discord you can't put a sentence together without typos?
And, as if that was not enough, I see absolutely no evidence that you have even tried to debug this code
Probably a random ui bug. Clear the error and see if it happens again. Resetting the windows layout might help if it occurs again.
yes i just did it thankyou for helping
yea no cap xD
Note that it is also against our #πβcode-of-conduct to ask questions about unverified AI content
Hello GoodMorning my friends
Hello, I wanted to ask if anyone has time to help me fix my game so I don't send it, but I would like to ask what I can change. I won't send it because I'm afraid it will be stolen. However, the problem is that there are so many little things that work quickly. I fix something, something else doesn't matter. I'd like to work through the entire game from scratch so everything is compatible, but I'm just a beginner myself and would need someone who knows Unity
If I want to access a class (call it Z) referenced in another class (call it Y) from a third class (call it X) (for example from a script that heals the player, and it access the player Controller and the UI Manager referenced in player controler) what is the more suited way to go? Make the class Z public in Y so I can get it from X with just the reference to Y, create public methods in Y to set anything I need in Z without the need a reference, make a reference for both Z and Y in X or it just doesn't really matter?
Otherwise I would always describe all the problems and then you can write me the solution or an alternative if someone is willing to explain it
That's kinda a non-question, ask something we can help you right now if you have an actual concise doubt about it
Just "fix my game" is basically asking for genie to grant you a wish
No, that's not what I meant. Of course we have to do it together, step by step, but because it's so much, I thought I wouldn't ask because I'm bothering people here and nobody wants to help
I have to take a quick look at the game and browse through it, then I'll ask if you can give me just 10 minutes
"Google Translate is not the best lol"
I dont think this is the correct code
for the saw?
Youre supposedly using some kind of AnimationEvent somewhere
i'll check
Or ur working on an AnimationEvent with missing information
As it doesnt give any specific file where this error occurs it might be the latter
I don't really know i'll keep checking
does it have anything to do with one of my documents?
in this maybe?
Dear lord, you're making me remember my programming exams at uni.
Depending on the situation, I either inject the reference I need, get it from a static reference manager, or if there is something in between the reference I need to access (X needs Z, X->Y->Z) then I either just grab it via a property/method in Y or call a method which Y/interface implements in order to do things with Z.
It doesn't really matter as long as the code is easy to understand, modify and expand if needed.
If I'm not sure, then I try and make it as simple as possible, so if I ever encounter any need to change it so that it can support other situations as well, I won't need to rewrite half of my project.
In this kind of situation, I'd probably let the player handle changing the UI and just call a method to modify his health
This is my goto which is this service locator pattern. It's either that or using some manager in between that binds delegates but that's so much extra effort, though it still has its uses by making stuff more detatchable (like UI in this case)
I though the more manageable and scalable is just make the UI reference public; but I have been told to avoid making stuff public if possible so, not sure here...
how would i put in a collision detection system
basically rn i have an enemy that teleports, and teleports randomly until it reaches a valid location, before spawning a smoke bomb effect
One way or another you need access to your methods from other scripts, you can be classy and use delegates or pass by interfaces, or just grab the references via statically
it spawns the smoke effect every time the enemy teleports, instead of when the enemy exits its teleportation state
how would i add a check to make sure the enemy is not in a teleportation state
Is there actually any reason to not put everything public? It does help modders (tho Harmony and Traverse exist)
Maybe private stuff that can break easily
if somethign that doesn't need to be used outside of a script it should be private
I mean, it probably has very few uses from outside the player Controller, mostly health and score and some visual effects. Maybe a menu in the future? Dunno
Probably should just create a method to heal instead of just one for taking damage, that should do it
Does the enemy has a way to detect when he has spawned on a valid possition? Like that is something that It does rn or It is what you WANT it to do?
Because it makes things harder for you as a developer. If all the inner details of every class is public, then you need to understand all the inner details of every class at all times to know which fields and methods are actually relevant for outside scripts.
i made scripts to detect an invalid location, but havent made a valid location detector yet
I mean, you probably don't really care much about security if you are doing something small, so it is kinda more from readability and protect you from yourself later on
I don't really have a problem with that, tho i mostly break up my stuff in smaller pieces
which makes it easier for me to understand even if i forget about it
if youre using prefabs for stuff like enemies, you need to set sensitive stuff like health to private
Just make a courutine with a timer that spawn the smoke just a bit after doing the tp, and reset it each time the tp effect is called
So, for example, say you make an inventory system. You might store items in a List<Item>. But to add items to the inventory, you might need to do more than just add things to the list. For example, you might want to enforce a limit on the number of items, or weight of items. For that, you have the AddItem(Item) method, which does those things. But if you make the List<Item> also public, you might be tempted to just add items directly into the list, because you might forget about the AddItem(Item) method.
Oh yeah i just put useless stuff in private, i.e. stuff that don't need to be touched. i mostly talked about stuff that direct access wouldn't hurt
Yeah, is pretty much for stuff like that. But I honestly whenever I am going to call something I usually go to the definition first and click on the parameter to see where it is being used within the class
I just tend to remember how everything works
assuming i don't stop working for a few weeks
Well, then we're talking about the same thing. I don't know if I would call the List in this example useless, but I agree that direct access to it is not useful for outside scripts. I was just replying to this question of yours, which suggests you would never use private:
Is there actually any reason to not put everything public?
You do for a game that you have been doing for month. Would you remember after a year? What if you are working with someone else? What if someone else wants to later edit your code?
That's the reason
If you are confortable using public go on
Is just good habit to avoid it
it can make debugging your issues a nightmare
i'm working the way i do because i'm alone. if i was working with someone else, i would adapt
in fact i'm working on mods with other people and we have guidelines and such
That's how I feel on life, I live alone with other people π
That honestly is pretty close to how i live
In any case, making things private can make debugging your code a lot easier, if only a few certain things can be accessed from outside the script you don't need to search a ton of stuff to see whats potentially effecting it
I have a menu script that requires me to drag and drop many public GameObjects or panels into it, which is fine. The issue arises because these objects exist in the world and everything works there, but when I need to apply this to the main menu scene, it also requires these objects to be present in the main menu.
How can I solve this problem, or what do I need to change?
π¦
Or to put it another way, how do you do it?
If these objects are essential for the proper working of the menu, then you have no option but to have them in the main menu scene as well.π€·ββοΈ
There must surely be an easier solution to this. also performance-friendly
If everything has to be loaded in the background to work, that's performance intensive, but writing another script for it just ruins the overview
Well, if your main menu depends on objects in the world, then it's a poor implementation.
Think why it depends on them and look for a way to eliminate the dependency
At least in certain situations(like a different scene)
Hello, it is not really a code error but here is my issue:
I cant rotate my camera around on unity. I can only go up, down, left and right, but not rotate to different angles. It used to hold right nouse button and move mouse around but it is not working it is just moving left and right. plz help
Not a code issue? Is this related to the main editor camera then and not some ingame camera?
- Click Layout at the top right
- Then in the DropDownMenu select Reset All Layouts
I also had the bug sometimes and was always able to solve it because the unity control somehow didn't work
okay, I will try
please tell me whether it worked or not
It didnt work π¦
So if you hold down the right mouse button (1) you still can't look around?
ur heart rate needs to be in the 80 -85 range for it to work correctly π
Nope, if i hold right mouse button down, it just moves side to side π¦
It was 120 earlier, there was a tornado watch and the weather was bad
id hate having that on my screen
i know i stress enuff no need to remind myself heh
but yea i see ur drag box when u right clicked.. it shouldnt do that..
Sorry, then I don't know what we can do next, but there is probably someone here who knows more than me, for me it always worked when there was something wrong with the controls
you dont have probuilder do u?
click this lock icon
ur axis' are locked
omg tyyyyyyy
np mate
LOL i never wooulda known
yea ive had that issue once.. its hard to discover since the icon is sooo small
also, ty Hungriger for helping too π
no problem, I'll help you and you help me. That's what the discord is for, we learn together and help each other
π
Hey, guys! I got an issue here. So, whenever I click the play button on my main menu scene I see that. Check my code as well.
So there is no gameobject called Player
Yes probably in my main menu scene
Do I have to like maybe copy paste from the other scene my player game object on that scene?
My game manager prefab is used across the other scenes
That's why I ve made it as a prefab
And the other managers
I am having another error again. Mild NSFW
Sorry, I'm still new to using interfaces. I've used them for a method before and it works fine. Why is it not picking up on that string right there?
This is what my interface looks like:
{
//Interface for general actions
public interface IAction
{
string actionName { get; }
void Cancel();
}
}```
Should I make a whole method called GetActionName() and within my action scripts do
```void GetActionName()
{
return actionName;
}```
I'm sure this will fix my problem but I'm wondering if there's a simpler implementation
Nevermind, I just realized that void GetActionName actually has to be string GetActionName and it'll end up not fixing my problem
oh it just had to be public π
You're experiencing the problem with shoving all kinds of unrelated functionality into one big mega game manager script. Make things more modular or rewrite your code to expect that things don't always exist.
can anyone help me with these two problems that i have, the first one being when the enemy collides with the player the player just drops down into thte tiles and the second problem being the enemy just phases through the walls
my enemy is meant to track the player when it enters it its perimeters and it does do that successfully
however if i wwalk upwardsyou can see what the enemy does
google tells me that this is a problem of Unity. How do I fix this? Because my code works so far everything
yes, unity bug, restart your editor
I did it yesterday and it always comes back ^^ thin i need to fix it π
it be like that sometimes
the only thing you can do to fix it is to not have any windows open that use graphs
try a different version
Is there a big difference? because I use : 2022.3.6f1
I can't upload! idk what is wrong
yes, upgrade to the latest 2022.3 version
Okay thanks i try it ^^
with unity, how do i configure visual studio permanently
like i configure it but everytime i re launch it , i gotta do it again
π€ you (should) only have to do it once . . .
Try launching Unity as admin and changing the settings then
I assume the default editor option is not saved
alright thanks
can anyone help me with this
quite stuck
how do i stop a child from teleporting with its parents
Unparent it.
Sounds like incorrect movement logic that doesn't comply with physics.
hello, running into a small issue with something, im trying to make it so when i pick up a coin the value changes using scriptable objects, the item count on the scriptable object increases but the text doesnt update when i pick up the coin, ive looked it up but i keep running into the same issue where the value in game doesnt go up and remains at 0
First configure your !ide if you want 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
β’ Other/None
How can i rotate the axes from an Transform?
i have it configured tho, im using the version that got installed alongside unity
This says you do not
It's errors
Yes, I know, but can you help me fix it?
i got erros
Well, start from reading the errors, the callstacks and looking at the line of code that throws them.
Error 1
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, UnityEngine.Vector3 pos, UnityEngine.Quaternion rot) (at <f7237cf7abef49bfbb552d7eb076e422>:0)
UnityEngine.Object.Instantiate (UnityEngine.Object original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at <f7237cf7abef49bfbb552d7eb076e422>:0)
UnityEngine.Object.Instantiate[T] (T original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) (at <f7237cf7abef49bfbb552d7eb076e422>:0)
Effects.PlayExplosion (UnityEngine.Vector3 position) (at Assets/Scripts/Play/Effects.cs:10)
BulletScript.Die () (at Assets/Scripts/Play/BulletScript.cs:49)
Code
private void Die()
{
PlayAudio("Explosion");
effectsScript.PlayExplosion(transform.position); <---
Destroy(gameObject);
}
The cause is self explanatory:
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
And looking at the stack trace you can tell that it was thrown by UnityEngine.Object.Internal_InstantiateSingle which was called from UnityEngine.Object.Instantiate, which was called from UnityEngine.Object.Instantiate[T] which was called from your code Effects.PlayExplosion in file Assets/Scripts/Play/Effects.cs line 10.
Please help me with these errors
for both of the errors?
Read the error, check the code.
i did
Yes, although it's not errors. It's bugs.
@teal viper okey i try it
Great, so find the missing reference and either make sure it's assigned or that you make a null check.
What line throws the error?
16
yes
What does null reference exception mean?
i don't really know i am new to this
I can't upload for some reason π¦
What does reference mean?
em
!vrchat
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
like to copy the address of the argument?
i can show you my code, i dont quite understand where here it causes these bugs
A reference is not a verb. But you're close. It's a variable that holds the address of an object. It points to the object.
What does null mean?
Sure, share your 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.
oh
Null means like you have to put some value to it?
No.
null means
I suggest going through the C# basics.
There's not much we can help you if you don't know what a null is even.
i mean like it's going to be zero untl you put a value
ive set to patrol routes and the enemy patrols them , until a player enters the perimeter , after that the enemy tries to chase it
That doesn't explain what a null is.
Sorry
OK, most of the erros are gone but I still have one
Error2
NullReferenceException: Object reference not set to an instance of an object
CoinScript.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/Play/CoinScript.cs:34)
CoinScript
if (other.gameObject.CompareTag("Player"))
{
Destroy(gameObject);
PrefsSave.instance.IncreaseCoins(Value); <-------
}
if (other.gameObject.CompareTag("Meteor"))
{
Destroy(gameObject);
}
Prefssave
public void IncreaseCoins(int value)
{
currentCoins += value;
PlayerPrefs.SetInt("Money", currentCoins);
UpdateUI();
}
i hope someone can help me
No need to be sorry. I'm not asking these questions to blame you or something. Just learn the basics properly and you'll see how easier it is to get through these kind of errors.
btw dlich heres code https://gdl.space/icuwipubiy.cpp
What line throws the error?
as soon as I touch a coin
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Player"))
{
Destroy(gameObject);
PrefsSave.instance.IncreaseCoins(Value);
}
Oh, I see the arrow. Okay. Well, what on that line could be null?
i dont understand?
I am actully like seeing the environment of unity engine and my uni is going to start with c# ( i know i can start right away) my uni has actually told us to create a 2D platformer game so i was going throught a yt tutorial for that but i am stuck on this erroe so i was asking for help
You're using transform to move your object directly. That's gonna ignore physics.
transform.position += direction * movementSpeed * Time.deltaTime;
Use some physics compatible method to move it instead.
i am very new to unity and C# but i will go through some basic
i was wrong i just want to turn the vecctor 90 degress in the left. Is in 2D.
Well, what does null reference error mean?
thankyou for helping
NullReferenceException: Object reference not set to an instance of an object
CoinScript.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/Play/CoinScript.cs:34)
I've seen that before. I'm asking you whether you understand what that error means.
No, I don't know what the error means
What is a reference?
It's not unity. It's basics of C#. I suggest going through them before continuing with the project.
I don't understand why you can't explain it to me, because maybe I know, but I'll tell you another way, just tell me an example
Because we can't make a C# basics lecture here in the discord, it's not what the server is for.
All you have to do is write one sentence that explains it, but if that's too difficult for you, okay...
u mean flip it?
you have a reference that is null, now are you any wiser?
if its 2d and a sprite theres a flip boolean
Explains what? What a reference is? What null is? What a null reference exception is? That's already 3 sentences to write and they have some underlying knowledge dependencies as well. If I'm gonna explain everything here, it's gonna be a wall of text.
And all you have to do is google it and get access to more than enough basic learning materials, which are required to go through if you wish to have a pleasant time learning and using Unity
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types
YES
i want the vector to be flipped
i m making a shooting
script
to invert a vector you can multiply it by -1.
To rotate a vector you can multiply it with a Quaternion. For example to rotate 90 degrees clockwise on the Z axis you can do:
Vector3 rotatedVector = Quaternion.Euler(0, 0, 90) * originalVector;```
not sure what u mean by vector to be flipped then... if u want the vector flipped u can just change the vector
i posted a link w/ all the rotation methods earlier..
are you wanting to rotate this object? Or just a vector?
just a vector
looks like 90 degrees counterclockwise on the z axis to me
its 2D... the z points forward
if u rotate it on the z its flipping upside down
90 degrees counterclockwise on the z axis will get that image, assuming the arrow pointing left is the green arrow and the one pointing up is the red (they drew them as both red)
I can see how you are saying 180 degrees on the y
yeah
lol,, u confused me π
thanks
cool cool.. but yea.. check out rotation methods https://gamedevbeginner.com/how-to-rotate-in-unity-complete-beginners-guide/
as mentioned before
up here they said 90 degrees to the left which I read as 90 degrees counterclockwise around the z axis
Does foreach over List<> iterate in order?
yes
nice, I assume dictionary is a case where it doesnt?
Yes, that's part of the guarantee of a List, it keeps things in the order they were added
does not
Correct, Dictionary is not ordered by definition
Dictionary does not have a order
Cool, I knew that one of them is not in order and needed to be sure since I am writing a priority list and its important that it happens in order π
if you wanted could used a OrderedDictionary or keep a list of keys
generally if it has a index it is ordered
Ah yes thats what I remember.
What is sorted list tho?
It seems to be a dictionary?
what is the exact type you are talking about
SortedList is really a sorted binary tree
IDK why they call it a list
it's almost the same as SortedDictionary too
you will prolly never need to use that type
Alright, good to know, thanks. I will keep using List since it does what I need it to.
List if you want a list of items, that is ordered or you want to access by index
Dictionary, if you want to access it by some other sort of key and do not care about the order
like a string key being common for accessing it by a id or name
Yep I use that, recently I even used HashSet since I needed a dictionary without value.
sorted list is not binary tree
https://github.com/microsoft/referencesource/blob/master/System/compmod/system/collections/generic/sortedlist.cs#L177
it is just a list
fine it's a list that maintains internal sorting
SortedDictionary is a tree
but they have almost identical APIs
your error message is telling you exactly what the problem is
you can't call new GameData(); in the field initializer like you have there
you need to do it in a method like Awake or Start
It's written in the error details
the line where the error is obviously
the line where you have written new GameData();
It even says at "path":line number
I'm having trouble adding my maze generator to a background sprite so that it draws on the background instead of at the empty object and the ways I've tried haven't worked well can anyone help with this?
Im trying to fix this code where when i collect a coin, it gets destroyed and adds to my points, i dont know what the problem is and how to fix it
It's a bog standard null reference exception
- Looks like the thing you collided with doesn't have the "PlayerCollectCoins" script attached to it.
- Your IDE is not configured
What text editor is that?π
yeah idk why the colors went away
Fix it:
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code
β’ JetBrains Rider
β’ Other/None
it was just colored 2 mins ago
If it was working, kill the editor and reopen it
ok its fixed
Hi, I have a shader that changes the a render texture that I use to render the screen tot he player. I want to store those changes and apply them back to the main texture. Sort of to keep the effect and create a permanent change on what the player is saying. I'm using a render texture and a temporary render texture to store the changes, then applying them back to that main texture. I'm in Unity 2022.3, using URP.
`using UnityEngine;
public class ShaderTextureUpdater : MonoBehaviour
{
public Material material;
public RenderTexture mainRenderTexture;
public RenderTexture tempRenderTexture;
public string mainTextureProperty = "_MainTex";
void Start()
{
mainRenderTexture.filterMode = FilterMode.Bilinear;
mainRenderTexture.wrapMode = TextureWrapMode.Clamp;
tempRenderTexture.filterMode = FilterMode.Bilinear;
tempRenderTexture.wrapMode = TextureWrapMode.Clamp;
}
void Update()
{
Graphics.Blit(mainRenderTexture, tempRenderTexture, material);
Graphics.Blit(tempRenderTexture, mainRenderTexture);
material.SetTexture(mainTextureProperty, mainRenderTexture);
}
}
`
This doesn't work for some reason, anybody got any idea why this might be?
I wonder if Graphics.Blit doesn't work in Unity 2022.3, but that sounds a bit farfetched.
if i collect Gem 2 first it works that my gemcount is 3 but if i collect first gem 3 and then i collect gem 2 gem count is 3 and if i collect the last gem gemcount is 5 idk why he count +2 if i collect a other coin first anybody know what i did wrong ?
learn arrays my friend
your code should just be:
GemCount++;
gems[GemCount - 1].SetActive(true);```instead of that big `if` chain.
they can also all just have the Gem tag.. don't make a different tag for every gem
array better in start or awake ?
I don't really understand the question
did it but it resolved not my problem. Wait a moment pls
Just to refer, whenever you want to destroy a game object you actually don't have to destroy it, as well as with instantiation. I know with that I am not helping you with your current issue but what I mean is it is better to disable and enable your game objects wherever you want rather than destroying them, for example if you have game objects to instantiate it is better to use Object Pooling method for these purposes π
My problem is when I collect the coins in a different order. Suddenly, the other coin no longer counts as +1 but as +2. I had an array before, but that didn't work either. This is the array I had before
ohboy
sounds like an unrelated bug
Where is this method being called?
Also why would gemCount be less than zero?
We usually use !code to show our code, unless you want to show syntax errors
π 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.
So let's break it down. If smth collides with a gem, this gem gets destroyed and a random gem is set active with a 33.(3)% probability.
That's the exact probability for the same gem to be destroyed and spawned, causing it being collected 2 times
and how i fix that
I am not a prophet, I don't know what you want to achieve
You may call a random gem which wasn't the one something touched?
He counts a gem as 2 even though each gem should only be counted as +1. There are 3 gems in the game and when I have collected all of them the count is at 5
the first gem always count +1 but the secong and thierd count as +2
ah wait mb i fogert that i have 2 colliders at my palyer xD
I see, I accidently wrote "a random gem". The gem with gemCount index is activated.
lmao thatβll prolly do it
The first gem will be counted +2 if you collect the gem with index 0
It won't fix the issue though
might fix it counting the gem as more than what it should be
you have to get the instance of the collected gem to not activate it, probably
Well, I guess it'll count the gem at least 2 times then
hello, are any of you familiar with greedy pathfinding
I guess Djikstra's is greedy
mb sorry
I've recently implemented A*, so I hopefully know how it works
(yeah, they're different algorithms, but they have the same vibe)
set h to be 0 no matter where vertex is, then it is djikstra
right!
did you make node grid to that?
No, this was for goal-oriented action planning
which creates new states to explore as it goes
so there's no "pre-existing" graph
All you need for A* is a set of nodes you haven't visited yet!
Hello! I am trying to play a timeline when I'm in trigger. Here are my codes. This for Player https://hatebin.com/pubfetlzaa, and this for Timeline https://hatebin.com/stsvczunrj. Is this a wrong approach? If so how can I improve on it?
Hey guys
I have this Bool variable.
If the raycast shot from Player hit the target, I'll set this to true.
In another class I have this Bool variable to store the Bool from the other class I showed above
But it seems like the Hit is not receiving from HitTarget ?
Is there an error
Try to put the bool first
are you expecting Hit to change when hitTarget does?
Before you instantiate
If there's no error and the second script exists at all, then you're definitely setting Hit to controller.HitTarget
Whatever value controller.HitTarget has when this script starts, Hit will have
If it's working, i'd be able to destroy the target
Nothing in any of the code you've provided has anything to do with destroying anything
No, I just want Hit to be true when Raycast hit just like hitTarget
all you've shown is getting a boolean in Awake which, unless there's errors, is definitely happening
I think he needs to put the bool first
so this Awake runs after HitTarget is set to true?
What do you mean "put the bool first"
Before he instatiate the object
I mean before he instatiate the object
Ah, I see what you mean. I don't actually know what object the second script is on, it could be on that vfxGreen object
Yeah, there's a good amount of ambiguity here. @brazen canyon maybe you should provide actual context and !code, which objects and which scripts these are on, and what you actually expect to be happening that isn't happening
π 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.
Yeah cause C# reading from first to last line
Right, I just assumed this script was on an unrelated third object, but it could very well be on the thing being spawned
Wouldn't you use if (Physics.Raycast(ray, LayerMask) if you're trying to see if the ray hit anything specific and then set the bool to what you need
If it was on a third object it would be also incorrect, unless it spawns it with that object due to awake
Right that's what I'm trying to figure out
Okay so what is supposed to be happening but isn't
Hey everyone which unity course I should take to learn advance scripting and game development?
No I don't think so, I want the Hit to be true when hitTarget is true, Hit to be false when hitTarget is false
so you do want Hit to change when hitTarget changes
I'm putting this script in the target prefab
Is that the thing you're spawning in the raycast
Unity learn programming pathway
Can you send me link pls
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
I want particular course link
It suppose to be like this, the target jumps around.
I wrote this method in one script with the TPP Controller so it worked, but it's hard to change things so ...
Yes
There shouldn't be any issue to find, quite beginner-friendly
https://learn.unity.com/pathway/junior-programmer
then don't have a Hit variable and always use controller.HitTarget
Oh yeah that Instantiate, I didn't remove it, so just pretend it's isn't there
@timber comet i have seen this course now I want to learn advance game development scripting so i can make tycoon type game so any course for it ?
Why is that ?
You already know the basic of Unity?
Making a tycoon game is very difficult
because when you do Hit = controller.HitTarget you are making a COPY not a REFERENCE
Ohhhhhh
Yes
Yes I have made over 8-9 games and also did freelance work
I think if you search well enough you can find some tutorials for tycoons games, but I do not recommend it
Now I want to learn advance so...
Wonβt learn anything
I don't know from where to start making
These tycoon type game
Okay, so, whenever this Target prefab is spawned, it will read the TargetHit variable from the TPPController script on that object and copy the value over
Got it, have you finished and understood them all perfectly? Even though, I don't think you already have enough knowledge after completing this pathway. Maybe you should try either creating your middle-level games while also learning something new or using some youtube tutorials before doing something too advanced?
Ya can you send me some good yt tutorial π
He should learn singletons, β¦
Intermediate level
I donβt remember how they are called
Sounds about right.
But Mr.SteveSmith said that I'm just copying not reference-ing ?
So am I
You're getting the value of TargetHit at the time the code is running and storing that value in Hit
Dear everyone, I hope to get help from you. I am building aviator crash game, but I am a beginer so I don't know how to do it,
Currently I have built like this
Now I don't know the graph function for airplane, would you please help me this one?
any tips will be fine.
Singletons is something that allows to have a some kind of "static" instance for a non-static class. I don't think this's a great explanation though. They usually look like this:
GameManager.Instance.MyMethod();
You can find a plenty of tutorials (not necessarily on youtube)
@willow scroll can you send me some good yt tutorial so I can learn intermediate level project
But that sounds like what I need.
I'm confused ._.
So, you want to store the value this object's TargetHit was at the moment of its creation?
Nothing too special about Singleton
I want Hit to change when hitTarget changes
I want the Hit to be true when hitTarget is true, Hit to be false when hitTarget is false
That is not what is happening
You're setting Hit to whatever value TargetHit is at the time that line runs
No i am demanding some good projects to make in unity so I can learn intermediate level scripting not singletons
He already said basically what you need to know
if you want to use the value currently in TargetHit, just use TargetHit and don't make a new boolean at all
Try modding Unity microgames
!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.
nobody demands anything on this server
So I'll have to put it in update ?
Well, plenty of people demand. Whether or not they actually receive is different
Inefficient but yes, you could use an event tho
Why do you even have a boolean on this script if the entire point of it is to just be the value of another boolean you already have a reference to
Actions stuff ? ._.
Man I'm sucks at that.
Or just pass the value
which i s what I already told him
You do events if you want to pass the variables between multiple objects
But as he said, you can just pass the variable
I don't really use them, I can recommend you searching a specific topic you like e.g. "cookie clicker", "infinite runner" or "draggable objects", then just doing it, usually not just the full stuff copying from the video, but also implementing your own additional logic.
I can just suggest channels like Unity, Samyam and Tarodev
Oh that sounds really convenient
Yeah it is, + it only does this when needed, so it wonβt check every frame for something changing
what do I do if I have a building player failed error but no other errors supporting it?
But it's also incredibly overkill for what should just be using the reference you already have
Just pass the variable, as I said you should use events only if you think or know you will use something that multiple object needs
So for example, if you need to check if the player dies to stop some game logic and to show some uis, just create an event: onDeath, you add the listener, and after that you donβt need to call multiple functions for the same thing
What is the bug?
What does "loading so ??" mean?
Yes, no plan, I don't even have that many objects, but it's there and then it loads
Do I need a loading screen or have I made a mistake? What do you think, when do you use a loading screen or can I not preload all objects?
I don't know what the issue is. I am asking you to explain.
Nothing looked wrong in that video
You clicked play, it loaded the next scene, you played, you died, a death screen showed up?
Everything looked like it worked
When I pressed start the game froze briefly for 1 second or just 0.5ms but I don't want that
look at the astronaut
Thatβs just the time for loading the scene
Load the scene asynchronously then
But that is very normal and expected
Not a bug. A LOT of games do that haha
Yes, it takes 2 seconds on my cell phone and I can't preload it
what is asynchronous?
If it takes more, better doing a loading screen tho, otherwise it will seems like your game froze
Basically it loads something in the background
Thank you
Eh. Just pop a text that says loading and it's all good imo lol
But yeah, SIGNIFICANTLY longer, do a loading scene
I'll take a quick look, thanks for the link β€οΈ I'll get back to you later
Right
what does { get; set; } actually mean in an interface?
It specifies a property
In an interface, it means anything implementing that interface must implement a property by that name with a get and set
interfaces cannot declare variables but they can declare properties
oh how can i share a variable through scripts inheriting from my interface then? i looked it up and all i was seeing was get; set;
yes that will work, a property is just a fancy variable
Interfaces cannot declare variables. Properties are the closest you'll get
wait so why isnt this working?
interface:
public interface IPickupable
{
bool pickedUp { get; set; }
void Pickup();
}
item script: https://gdl.space/xuxuyonowo.cpp
Use an auto-property with { get; set; } and the compiler automatically creates a variable (a field) the property will access.
what can you not set it inside a seperate script then?
What doesn't work about it
define not working
when i pick up an item i can still pick up another one
so i can pick up 2 at a time which is unwanted
the script that picks things up needs to keep track of whether it has already picked something up
and not try to pick up a second thing
Your issue is unrelated to using a property instead of a field
yep just a basic data/logic issue
I think he wants a static variable, that wont work with an interface
ah right so just inside the item script itself?
Are you expecting them all to share this variable? That's not how variables work
the item script? No, in the script that picks items up
yeah i was
for example you might have a Item currentlyHolding; variable to track the item you are currently holding. If it's null you know you're not holding anything and can pick something up.
okay ill have a go cheers
hello, is the HasKey method useful here ? or i should delete delete it
What do you want to put into that variable if the key isn't present?
i want 0
If I remember correctly you can use .GetInt("Force", 0) - the second argument is the default value if the key isn't here
ok thanks :)
This is more of an animation question, but I wasn't sure where to ask, and I figure what I'm trying to do overlaps with something I could do in code: is it possible to set an offset on just one layer of a multilayer asset (such as a .psd)? The aim is to have just one material/texture on the object, but have the "eyes" mapped to a transparent part of the texture, with a variety of eye textures below it that I can switch to on the fly.
If it makes a difference, this is for a vrchat avatar.
you can always just change materials on the fly or swap the texture on the material out on the fly
RenderTexture renderTexture = Render3DObjectToTexture(obj);
if (renderTexture != null)
{
rawImage.texture = renderTexture;
}
private RenderTexture Render3DObjectToTexture(GameObject objPrefab)
{
RenderTexture renderTexture = new RenderTexture(Screen.width, Screen.height, 24);
GameObject cameraObject = new GameObject("RenderCamera");
Camera renderCamera = cameraObject.AddComponent<Camera>();
renderCamera.targetTexture = renderTexture;
GameObject obj = Instantiate(objPrefab);
obj.transform.position = renderCamera.transform.position + new Vector3(0, 0, 10);
obj.transform.LookAt(renderCamera.transform);
renderCamera.Render();
Texture2D texture = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGB24, false);
RenderTexture.active = renderTexture;
texture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
texture.Apply();
RenderTexture.active = null;
// Destroy(cameraObject);
// Destroy(obj);
return renderTexture;
}
Hi, why is it only showing the render texuture when im not destroying the camera and object?
did you read this?
https://docs.unity3d.com/ScriptReference/Camera.Render.html
yes, thats what i did
[SerializeField] DEBUGCursor cursorInstance;
...
if (cursorInstance == null)
{
Instantiate(cursorPrefab, hit.point, Quaternion.identity);
}
How can I store that instance of cursorPrefab I just instantiated in my cursorInstance variable?
reference the prefab as a DEBUGCursor, not a GameObject
Instantiate returns an object with the type of the object you gave it
so if cursorPrefab is a GameObject, you get back the GameObject
You can reference a prefab as a GameObject or as any component type on the root of the prefab.
Yesyes. I want to instantiate this GameObject, that is prefab'd, then immediately store it in a variable
If cursorPrefab is a GameObject, passing it to Instantiate will give you a GameObject.
So make your prefab of type DEBUUGCursor as Fen said
You can't store that in cursorInstance.
But if cursorPrefab is a DEBUGCursor, then Instantiate will return a DEBUGCursor
So I just changed cursorInstance into a GameObject, right?
That is the opposite of what I suggested.
I said you should make cursorPrefab be a DEBUGCursor
I presume you want to do things with the DEBUGCursor component.
Not really, no
I don't think you're actually reading any of the answers you're being given
If you literally don't care about whatever cursorInstance is, then I guess you can make it a GameObject. This is fine if your game doesn't care at all about what components a debug cursor has
But that's not very common.
I'm reading the answers. I realized my first mistake was that they were of different types; but I'm not doing anything with the DEBUGCursor script
I would still prefer to reference the prefab as a DEBUGCursor
This means I can't assign something that isn't meant to be a debug cursor to the field
and if I wind up needing to put some logic on a debug cursor later, I don't have to make any changes here
That's fair. I should do that
I almost never refer to prefabs as a GameObject
none of these are prefabs, but the same idea holds
all I do with these things is active/deactivate and move them
So now both of them are of the type DEBUGCursor. What's the syntax for me to take Instantiate(cursorPrefab, hit.point, Quaternion.identity); and store it in cursorInstance?
(I'm really sad the server doesn't allow me to post just "=") π
=
really? Then you obviously missed this bit
you could of just said that i forgot to disable my camera π€·ββοΈ
I could have, yes, but you are supposed to read documentation so that you learn
what does "=" mean in this context?
The answer to the question
That's how you store the new object in a variable
I was going to comment on that, but I was surprised that destroying the camera would have an impact after calling Render()
Got it, thanks
Does anybody have any experience with using navmesh in unity?
ah, but you aren't actually using texture at all; you're returning the render texture you created (which is going to be a leak if you don't dispose of it). Perhaps that's how the spooky time-traveling behavior happened.
Ask your question.
I have a problem with my project. I'm using vuforia for area targets and I want to use navmesh to create a mesh for the floor so I can then guide the user to the destination. Basically indoor navigation
But the tutorial is outdated and the ai navigation no longer has the bake button
hello i was adding a rigidbody to a cube to not skip the wall but its stuttering and not move can someone give me the solution plz !! no code just from inspector
i've disabled it and it still dosnt show it
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New Ghost", menuName = "Ghost")]
public class GhostInfo : ScriptableObject
{
public string ghostWord;
public int damage;
public bool isDead = false;
public void Initialize()
{
ghostWord = assignWord();
}
public string assignWord()
{
string[] wordList = { "perro", "gato", "casa", "libro", "silla", "manzana", "pelota", "coche", "mesa", "flor" };
int randomWord = Random.Range(0, wordList.Length);
return wordList[randomWord];
}
public void compareWord()
{
if(PlayerType.playerInput != null)
{
if (PlayerType.playerInput == ghostWord)
{
isDead = true;
PlayerType.playerInput = "";
}
}
}
}
Hello, I need some help in trying to understand why my boolean isDead is always true. To make it go true it gets compared with a player Input via an Input Field. This is the script:
void activateInput()
{
InputFieldObject = Instantiate(InputFieldPrefab, canvas.transform);
inputField = InputFieldObject.GetComponent<TMP_InputField>();
inputField.ActivateInputField();
inputActive = true;
}
void deactivateInput()
{
Destroy(InputFieldObject);
playerInput = inputField.text.ToLower();
Debug.Log(playerInput);
inputActive = false;
}
playerInput is declared as a static public string.
Using a script called Enemy, when the enemy prefab spawns, I call Initialize() to name it then on it's Update I check if it died or not.
void checkDeath()
{
ghostData.compareWord();
Debug.Log(ghostData.isDead);
if (ghostData.isDead == true)
{
Destroy(this.gameObject);
}
}
How are you moving the object
your code doesn't really make sense to me
you make a new render texture, then make a new texture, then read into the new texture, then...return the render texture
of course not, it's AI generated code that he's modified very badly and doesn't have a clue what it does
eh, it looks reasonably close to the example on the Camera.Render page
it's just wrong
we saw it when he first posted it a few hours ago
ah
Where do you assign ghostData
float movespeed = 5f
float xValue = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
float zValue = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;
transform.Translate(xValue,0,zValue);
Teleport-based movement doesn't play well with rigidbodies. If you want to teleport a rigidbody, you should get the target location and use MovePosition instead
Oh, let me show you, I was reaching the message typing limit, so I was trying to make it as short as possible.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public GhostInfo ghostData;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
checkDeath();
}
void checkDeath()
{
ghostData.compareWord();
Debug.Log(ghostData.isDead);
if (ghostData.isDead == true)
{
Destroy(this.gameObject);
}
}
}
All the component assignement parameters have to be referenced manually in the inspector each time, which is... very inefficient considering I have to create like several dozens for these scripts. It is fine if I assing these references at awake or should I like... make an editor tool like a button to assing all of these in editor with just one press?
for physics dont use transform.translate or trasnform.position
You could share it on a bin site in the future so it doesn't hit any limits. !code
So, you're dragging in an instance of your scriptable object to this object, right?
π 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.
but the course i watch its used the same code but he use unity 2020 and me 2021.3
The version doesn't matter. Rigidbodies do not appreciate being moved by transform manipulation
I see that there are way too many people here with problems so if anybody wants to help me, I'm willing to pay at this point. I've been stuck for the past 2 weeks and it's driving me insane
Exactly. The thing is that the boolean inside the ScriptableObject is always true from the start of the scene, where the input field is empty.
so what should i use
Show the inspector of that scriptable object
bro i dont understand why you are so against helping like ive read through the docs to see how render textures & rawimages work and instead of actually helping, u say its ai code like ur forgetting this is the #π»βcode-beginner channel for beginners
It's true, but doesn't it change to false as I set it on false on the code?
Becuase if it doesn't, then this is the issue probably
Where do you set it to false
When I declare it on the ScriptableObject script. It's in one of my last messages
Here
You are setting the default value of IsDead to false
That is what value it's set to when you make a new SO
You never set it to false
That make me confused idk how the same code work with other person that i watch her course π
Did they add a rigidbody to the object
um hello, i have a question about jumps and running, I have a character in 3D that can jump and sprint, but when i jump while running, first the character doesn't keep its running momentum midair, and second i feel like when the character jumps while running, it doesn't jump as high as when im not running. Do you know why it does that? i can provide some screenshots if you need
He add the rigidbody to a cube to not skip wall
Hello, I am trying to enable a UI gameobject with a singleton only problem is its never awake until I call Script.i.SetActive() so its it ok to assign i in start or should I use something like
static FishingUI()
{
i = FindObjectOfType<FishingUI>();
}
Show the tutorial
No, do not use any kind of constructor. Instead you can make i a property that finds the object the first time it's accessed.
private static FishingUI _i;
public static FishingUI I
{
get
{
if (_i == null)
_i = FindObjectOfType<FishingUI>();
return _i;
}
}
Ah ok brilliant thankyou, just so I know for future reference why shouldn't I be using a constructor instead?
Hey! anyone got any idea how I could restart Time.time when the scenemanager loads the scene?
There could be a few reasons for that, without seeing any code, my guess is that you may be overriding the velocity instead of adding onto it - what does your code look like? You can use !code to post your script
π 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.
You literally cannot use a constructor for MonoBehaviours
Why might you need to do this?
Unity manages the lifetime of these components, so they can get executed at unpredictable times, even while not in play mode.
After a compilation, when exiting play mode, etc.
well because the time isnt getting reset on the UI when the restart game button is clicked.
Oh shit so anywhere where im using the Awake function to assign my instance I should change it?
and i want it to go to 0*
No you're good, Awake is not a constructor
You can use Time.timeSinceLevelLoad (if you're not doing additive loading or something, I don't remember the rule), or you can just measure time yourself
Constructors are public ClassNameHere() and static ClassNameHere(), notice that they don't have a return type like Awake does, it returns void
π 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.
thanks! that worked xD
Do i just write !code and copy and paste my script in it?
π 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.
Ahh got you, ok thanks very much for you help!
You can use one of the sites suggested by the bot to paste your code there, then you can paste the link in discord
{
Time.timeScale = 1;
tryAgainButton.SetActive(true);
gameEnd.SetActive(true);
}
public void RestartGame()
{
Time.timeScale = 2;
SceneManager.LoadScene(0);
}```
was trying smth and put Time.timeScale from 0 to 1 and the 2nd one to 2 and my player is running hella fast for some reason lol
example
If each value needs to be separated by a newline, you can join them with string.Join()
string joined = string.Join('\n', s1, s2, s3, s4);
// '\n' creates a newline
Else, you can use string concatenation or make an interpolated string to have more control over the format of your final string
a timeScale of 1 means 100% normal speed, so a value of 2 would be 200%, if your movement is based on time, it would make sense to move faster
well my movement shouldnt be based on time tbh lol
anyways, another problem i got is that the time starts from 1 and till it becomes 1, the ui for the time i got is blank.
{
if (Time.time >= 0)
{
timerText.text = Time.timeSinceLevelLoad.ToString("#,#");
}
}
public void AddScore()
{
scoreValue++;
scoreText.text = scoreValue.ToString("#,#");
}
public void UpdateAmmoInfo(int currentBullets, int maxBullets)
{
ammoText.text = currentBullets + "/" + maxBullets;
}
public void OpenEndScreen()
{
Time.timeScale = 0;
tryAgainButton.SetActive(true);
gameEnd.SetActive(true);
}
public void RestartGame()
{
Time.timeScale = 1;
SceneManager.LoadScene(0);
}```
anything i might be missing?
btw Time.time >= was to 1, just changed it
Im not too familiar with CharacterController as I usually use Rigidbody more, though I believe the general rules still apply, you would probably want to only apply Move once at the end, after all your calculations, and modify a Vector3 that represents your current movement direction and jump/gravity velocity, you also would normally want to apply deltaTime only once as well, this tutorial may help with implementing a jump and gravity, although the example is in 2D, since up/down is the same in both 2D and 3D (y-axis), the logic should work the same: https://gamedevbeginner.com/how-to-jump-in-unity-with-or-without-physics/
It also looks like your changing the position of your transform and also trying to set Move, you would normally want to do one or the other, depending if you want your movement to respect physics (using the CharacterControlllers "Move" func) or not (setting the transform position)
You probably dont need that if-statement at all, you could just update your text every frame, since timeSinceLevelLoad will handle a 0 condition if the level is not loaded yet
true, removed it
but still, time starts showing blank then 1
idk why it doesnt show 0 on restart
not to flex but i managed to writ this on my own π
https://hatebin.com/idukgybknd (200 lines OMG)
(with a very very few of questions asked here)
now i can legitimately help people on #archived-code-advanced 
congrats!
πͺ

a line is a line
you should consider using better names for your variables, as they are now they don't currently convey what they are supposed to be for. also any time you find yourself using numbered variables you should be using a collection like an array or list
they mean something in french but yes list would have been better
bfa6 means nothing in any language
is it a good idea to export my project as apk before it is finished, to show to friends for example ?
its the button assigned to the fa6 bool 
your UI should modify underlying settings data. when you open it up, it should check the state of that data and set its own fields based on that data.
you would need to show code. but you should be loading your saved setting in Awake and assigning it to the sliders when loaded
yes i know don't worry i'm just happy everything works fine
am I fair to style police here? because I feel like this man is going off the deep end
separate the UI from the state it represents.
That is a bit odd, it should show 0 by default after the first frame is complete, though I guess you could hardcode 0 in
so I should do 2 canvases and not all in one?
2 canvases?
multiple canvases is good
well... i don't think that's the issue though...
the issue is that they need some data structure like a don't destroy on load manager that stores settings state.
whenever any one element in a canvas changes, unity needs to effectively redraw the entire thing from scratch. So it is generally good to have multiple canvases, especially if you have one part of your canvas constantly animating
and then the UI should refer to that thing and set itself based on that, and control that data based on user manipulations of the UI
i am a complete noob but could'nt you use playerprefs ?
playerprefs is the devil
no
idk, it just skips 0 by making it just show blank and after that goes to 1. anyways, ill find a way to fix it i suppose lol
thats the code for it btw:
timerText.text = Time.timeSinceLevelLoad.ToString("#,#");
counterpoint: yes
the "cleanest" way is probably to use like a text file that you read and write, if you want to preserve the values across sessions.
then json maybe (my knowledge ends here)
playerprefs saves things to your registry. even if you uninstall, whatever you wrote stays there.
is it bad to export project as .apk before finished ? is it the way updates are done, juste replace the old .apk by a new .apk ?
tryna click the drop down icon for the animation but literally nothing happeneing???
so if you are KerbalSpaceProgram, and store a level file of several GB to playerprefs, and later uninstal KSP, KSP might still be taking many GB of data on your computer
make the app so good no ones wants to uninstall it
do you have the gameobject you want to animate selected?
oh thakns 
How can I add an event for when a Button is selected so I donβt check for that every frame?
Does this works if my script is not attached to my buttons?
I don't think so no
βCause I use only one script for managing my ui, which is attached to the canvas
nothing wrong with sending events from a ui child object to a main UI manager
K tysm
Can someone help me? If I set my options canvas to 0, I can open the option menu but nothing can be clicked. If I set it to 1, I can close it but the sliders won't move
as info the mainmenucanvas is at 0
and the loading screen to 1
Everything works in the world but not in the main menu
but why
this is a code channel. perhaps you want to ask in #π²βui-ux
I still have to invoke the UnityEvent someplace in my code right?
I invoke then I choose what to react in my inspector
lets say i have a variable called maxSpeed, how do i only add enough force to reach that speed
rb.AddForce(slopeMoveDirection.normalized * );
just add the force and in update, limit your velocity to max speed
and i also wanna implement acceleration
which is how fast the force gets added
Getting an issue where it appears like I'm being given access in the inspector to a parent's member despite it being private (but SerializeField is interfering?)
MyParentClass
private List<int> _myPrivateList;
MyChildClass : MyParentClass
private List<int> _myPrivateList; // specific to ChildClass, not overriding
The inspector shows 2 fields for My Private List
[SerializeField] is exposing a private member to child classes via the inspector
private members are still part of child classes, they just cannot be accessed or modified by those children
Shouldn't this be working? Is there any step I am missing? Cause the CustomEditor Tags are not being colored and the console is showing this error
configure your !IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code
β’ JetBrains Rider
β’ Other/None
so just lower the mass?
i think if you want to add enough force to achieve a certain velocity, the forcemode.velocitychange will do that, instantly
hello, there is a thing that i do beause i've seen tutos guys do it but i don't understand why.
Why do they always create an emptyobject, attach a script to it, then attach the emptyobject to a button, instead of attaching the script to the button directly ?
do you instead want a velocity cap?
or set or change the velocity
ok thanks so it's just like that ^^
Yeah but I can access and modify the private child member using an instance of the child class. SerializeField is allowing me to add/remove/edit elements of that private member through the child instance.
serializing values is not the same thing as being able to access and modify the private members in the code
Ok, so should I treat those members as protected basically?
that private member is still part of that class, as i pointed out. it's just not accessible within the code because it is not exposed to that class
why can't you directly set or change the velocity?
Protected from the perspective of the inspector? I know in code it still works normally
so you know how you can serialize a private variable despite it not being exposed to other classes? it's literally the exact same concept here
Oh gotcha, that makes sense
Can anyone help me, im trying to make a game and I need to change a variable when two gameobjects colide with eachother. I've attatched the code
why did you declare OnCollisionEnter inside of OnCollisionEnter
You have a function in your function
the warning you are receiving should have given you a hint towards the problem
let me test it now
So with this code its still not working. I might not have everything up the right way
is the log printing
do someone knows why this occurs, but only to the 4 last scenes i try to load ?
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MusclesMenuScene : MonoBehaviour
{
public string ForceMenu;
public string TricepsMenu;
public string DosMenu;
public string BicepsMenu;
public string JambesMenu;
public string EnduranceMenu;
public string VitesseMenu;
public string EquilibreMenu;
public string FlexibiliteMenu;
public void ButtonForce()
{
ChangeScene(ForceMenu);
}
public void ButtonTriceps()
{
ChangeScene(TricepsMenu);
}
public void ButtonDos()
{
ChangeScene(DosMenu);
}
public void ButtonBiceps()
{
ChangeScene(BicepsMenu);
}
public void ButtonJambes()
{
ChangeScene(JambesMenu);
}
public void ButtonEndurance()
{
ChangeScene(EnduranceMenu);
}
public void ButtonVitesse()
{
ChangeScene(VitesseMenu);
}
public void ButtonEquilibre()
{
ChangeScene(EquilibreMenu);
}
public void ButtonFlexibilite()
{
ChangeScene(FlexibiliteMenu);
}
public void ChangeScene(string scene)
{
SceneManager.LoadScene(scene);
}
}```
no its not
go through this https://unity.huh.how/physics-messages
i added the scenes in the build earlier
You do still have extra curly braces but those don't actually matter.
The Three Commandments of OnCollisionEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt not tick
isTriggeron either - Thou Shalt have a 3D Rigidbody on at least one of them
Jesus christ just make a function that takes a string
Why do you have so many functions
i love writing
well i have a 2d project so i have 2d colliders on both and I've done 2 and 3
you know why i am making this script ? i had a different script for each scene at start
Then why are you using the 3D function
Make a function that takes a string, remove every other function and every string parameter and just put the string in the button function
but why can't my scenes loads correctly
what do you mean? is the OnCollisionEnter specificly for 3d projects?
yes
The error tells you why
because one or more of your variables is not assigned to. and you do not have a scene that has no name in your build settings
did you not bother going through the link i sent?
Im doing it now
Hey guys
Does Static make a class accessible from other classes even though they're not in a same GO ?
Because it cannot load scene due to invalid scene name (empty string) or invalid build index -1
no, that's what the public access modifier is for
Static makes a variable belong to the class rather than any specific instance of the class
On top of what the others said, the keyword static (and other keywords like public private etc) have nothing to do with unity. There is no knowledge of being on a gameobject here
thank you, it works now
public access modifier ?
ok that's why x)
there are beginner c# courses pinned in this channel. you should start there
Now that you have identified the problem get rid of them so this doesn't happen again
https://www.youtube.com/watch?v=Hh1trmMO8zo!
does anyone know what's going on here?
code please
why do i do from here
i can't convert Button to String
i need a script that a slider working?
do you not have any scripts?
i havit a uicontroll for that
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIController : MonoBehaviour
{
public Slider _musicSlider, _sfxSlider;
public void ToggleMusic()
{
AudioManager.Instance.ToggleMusic();
}
public void ToggleSFX()
{
AudioManager.Instance.ToggleSFX();
}
public void MusicVolume()
{
AudioManager.Instance.MusicVolume(_musicSlider.value);
}
public void SFXVolume()
{
AudioManager.Instance.SFXVolume(_sfxSlider.value);
}
}
I'm desperate
i don't know how i could do without definying a function per button, since i have 9 buttons that haves to load a different scene each
Why do you have all of those button variables and why does your function take a button as a parameter
it was a bad ida but anyways i can't figure it out
Literally just make a function that takes a string and changes to that scene. That is all that needs to be in the script
Call that function on your button. Pass in the string.
you type it in
when you set the function on your button
A UnityEvent can pass a constant value to your function.
(for certain types, at least)
so this is enought ?
ints, floats, and strings for sure
Looks like you have code setting the slider's value
Yes now get rid of all of those string variables
then why ask about it here
well i didn't knew i could add a parameter identificator to a button
my script gone from 50 lines to 5
yes that's why the original was so apalling
at least a beginner coudl understand how it worked if he didn't knew a parameter could be added to a gameobject '-'
the new script is not beginner friendly
Fixed Update rb.AddForce(slopeMoveDirection.normalized * acceleration);
Update ```Vector3 flatVelocity = new Vector3(rb.velocity.x, 0, rb.velocity.z);
if(flatVelocity.magnitude > moveSpeed)
{
Vector3 limitedVelocity = flatVelocity.normalized * moveSpeed;
rb.velocity = new Vector3(limitedVelocity.x, rb.velocity.y, limitedVelocity.z);
}```
the thing in update is limiting the velocity, but its not setting the new velocity in the correct direction, which would be slopeMoveDirection
let's make sure we're both on the same page about what this is
onClick is a Unity Event
i think its just straight
UnityEvent lets you set up callbacks in the inspector.
A "callback" being a function that you call when something happens, basically
You are specifically flattening the velocity. You even call it "flatVelocity"
i don't know how to call these i "learned" in french :)
If you don't want to flatten your velocity, why are you going out of your way to do it
we're both on the same page
so that it doesnt take the y velocity into the calculation
ah, that can make it tricky (:
sounds good; i think you've got it!
So you don't want any Y velocity
thanks for your help ^^ (even if it gave me more work)
i've got this now but i cant jump
{
rb.velocity = rb.velocity.normalized * moveSpeed;
}```
this also works
but it makes my character bounce
when walking up slopes
im not sure why
let me send a video
this video is with this
how would i go about making an inventory script to simply hold my picked up gameobjects in an array and scrolling down or up equips them?
ive looked around for about 15 mins but couldnt find anything
and this video is with this
but here i cant jump
anyone?
i need this but without limiting the y velocity
Pretty sure you're gonna need to do some math. You can get the non-jumping part of your velocity with ProjectOnPlane using your slope normal. Then you can see how much greater your projected velocity is than your max speed. You want a vector with that difference as the magnitude, but in the opposite direction to your projected velocity. Then you add that vector to your original velocity, and you'll have slowed down your projected velocity enough that you're kept in your speed range
i already have the slope normal thing
slopeMoveDirection = Vector3.ProjectOnPlane(moveDirection, slopeHit.normal);```
So then you just need to do the second half of that. Where you get the "counter-force" vector and add that to your original velocity
Also that slope move direction is not your current velocity, that's just the direction
You specifically want the velocity vector projected on the plane, magnitude and all
any help on this one?
simplest way, have a holder on your player, where you have all the models of the items (the items which the player will see in his hand), make a script, just have an integer in there called ID, attach this script to the model in the players hands and on the object in the world, make them have the same id, and when you pick the object up with a raycast just disable the ground object so you cant see it since you picked it up, add the object to the items array, have another array of all the possible items (the items in players hands), and then just scroll through the items you have in the inventory and compare id's with the other array
use a float value to clamp then use that in Quaternion.euler
i know you explained it but could you help me out
im so lost
- Use ProjectOnPlane to get the current velocity projected on the slope
- Check if that vector's magnitude is greater than your max move speed
- If it is, subtract the max move speed from that magnitude
- Create a vector of that length, in the opposite direction of your projected vector
- Add that resulting vector to your original velocity
am i doing it correctly so far?```cs
Vector3 slopeVelocity = Vector3.ProjectOnPlane(rb.velocity, slopeHit.normal);
if(slopeVelocity.magnitude > moveSpeed)
{
}```
That's steps 1 and 2 so far
You aren't doing anything with the result
do i store it as a float?
Is it a float
then it would indeed make sense to store it in a float
hello! I'm getting this error after ive added, then disabled, and removed a script. I've tried reimporting everything, cleaning my cache, restarting unity editor + my PC, and I am yet to find a fix. This is happening both when I run the game, and in the editor.
error: TLS Allocator ALLOC_TEMP_TLS, underlying allocator ALLOC_TEMP_MAIN has unfreed allocations, size 208
log: Allocation of 38 bytes at 0000020790500110
EDIT: I FOUND A FIX
update: just had to update my Unity version LOL
i dont understand step 4
Do you know how to get the direction of a vector
not sure
slopeVelocity isn't a direction, it's a full vector
The direction of a vector is that vector normalized
That's the direction you want to use. The magnitude is the difference between your magnitude and your max speed
A vector is a direction times a magnitude
For reals, what am I doing wrong? Why is this not working? This is not overriding the Editor at all it isn't getting the reference to the Editor class to begin with and I don't know why
yes
Do you have any errors
Previuosly, yes; not anymore, the console is clear
id suggest to use proper variable names, "o" and "a" are quite nothing saying, does not help with readability
yeah i'll change them in a minute
im gonna read and try to understand more of what it does
so what's the issue
Vector3 o = -slopeVelocity.normalized * a;
rb.velocity = rb.velocity + o;```
Yep that should do it
That this is not doing anything, and all those calls to the Editor should be bolded
Show the inspector of a GeneralPowerUpLogic script in the inspector
when im on a slope and i jump now the jumps are weird
as to the highlighting, it's probably a misconfigured !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code
β’ JetBrains Rider
β’ Other/None
Like look at the class declaration, "Editor" white which I assume means it is not finding anything with that name
sometimes i jump higher and sometimes lower
Do your jumps take you straight up or do they jump you away from the slope
and on flat ground
they take me away
i want them to be straight
Once you're no longer touching the slope, you should no longer be using the slope's normal but Vector3.up for this calculation
Since you're no longer standing on angled ground
This inherit from it, shouldn't it show?
I don't actually know. Try changing it to this script specifically and see if it shows up then.
#βοΈβeditor-extensions might know more about what's going wrong if this doesn't work
Oh, it does show here actually
Do I really have to declare all the child script? That would be ridicolous
So it looks like it doesn't affect child classes. There might be a way to do that but I don't know it
You need to pass some param to the CustomEditor attribute if I recall correctly
the thing is im always going to be on a slope
my terrain is going to be curved
Not when you're in the air
Hello
https://pastebin.com/rcu9LVQy
I have a script here that adjusts the UV of a white vertex color on the mesh (I have the mesh as one object to save resources, making the eyes white in the vertex color helps the script target which part)
The only problem is that it scrolls on the UV weirdly on the eye instead of tracking the bone
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.
Seems like it
That's all I got
alright
This looks pretty normal to me
especially if your jumps are away from the ground instead of straight up
Oh, it just needs to add a bool in the declaration to affect the children; it would have know if sooner if it wasn't cause vs decides to not identify the Editor
Thxs
thing is this works perfect, i just cant jump
I'm trying to figure out how to get the layer system for the camera to work to make it look like carried objects are not clipping, but I use URP so I dont see how its doable
Cause y velocity is included in those calculations, so it's clamping your vertical velocity too. You probably want to clamp x/z movement only
urp can stack cameras, no? https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@17.0/manual/camera-stacking.html
I cannot like... attach a variable to a string in the inspector like this right?
but then this happens
#π»βcode-beginner message
that was with this bit of code
im not sure why my character was bouncing
when walking up a slope
It always does by default on slopes
You have to send a Raycast down and detect the normal of the slope and change the force vector to work on that direction
If slopes are not neccesary I would HIGHLY encourage you to avoid them
thing is i have 90% of them done
Do you not bounce in the other slopes?
I think you are just trying to clamp velocity in the object axises, while the force is been applied in the normal vector
I mean, I would clamp the speed overall and then, in the next step ,add the Y axis force that doesn't need to be clamped for the jump
Well, yeah. This will keep your y velocity same as when you were grounded, i.e. 0. So if you move down the slope it will make you bounce.