#💻┃code-beginner
1 messages · Page 54 of 1
I mean I have never seen such problem even though I had worked with Animations before
Thanks for your suggestions
I want to get rid of 'MENU' when I click the play button, can someone tell me how this is wrong? the script is in playbutton
You don't actually disable it anywhere
what do you mean?
Exactly what it sounds like. You don't disable the menu anywhere in your code
Oh, there was another screenshot
didn't notice it. That's why you should share code properly
!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.
So, seeing how the second log is not printed, MENU seems to be null.
Did you actually assign it?
The reference to MENU. Otherwise how does it gonna know what to disable?
ok thanks
does any1 know why my text is just gone?
Perhaps the error in the console is relevant?
no
Are you sure?
Okay.
I thought it would warn you about it, but you miss a font asset in that text component.
Did you actually import tmp essentials?
Or read that window message at all? 😄
Yeah. Don't ignore messages popping up on your screen. They're ususally important.
noted
Hey guys. What would be a way to say for example, if my character gets 100 exp he will level up? Because if I write something like cs if (experience > 100) { give 1 level } it will give me 1 level non stop. and if I use experience == 100 but I have 98 exp and now I have 102 it was never 100, so what would be a logic to make it work?
it will give me 1 level non stop. and if I use
Sounds like you are checking this in update constantly, which you really shouldnt need to do. Give them xp, level them up, remove 100 exp on level up
if (experienceToNextLevel >= experienceNeeded) {
giveLevel();
experienceToNextLevel -= experienceNeeded;
}
Something like this should work^^
probably not = 0, subtract 100 so you dont lose out on overflowing xp
oh ok, and I can maybe store the all time experience in another variabvle
and reset the one to check if level up to zero always
good ok thank you
true, just whipped it up real fast
great thank you !
what is the data type for a variable to store the time and date a new profile was created?
I tried DateTime but it just wants to auto complete to DataSetDateTime which isn't it
System.DateTime
fyi if you google C# DateTime and look at the MS Docs page it tells you which namespace you need
no but you can use the .Ticks property if you want to serialize the data
https://gdl.space/ifuyevojun.cs
not sure if this question belongs here, but does anybody have an idea why this wouldnt work in build but would in unity?
you're gonna need to be a lot more specific in your question
Wdym by "work" and "not work" exactly?
!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.
well, its a script I shamelessly stole on the internet that bakes lightning into prefabs
the newly baked maps do appear in unity play mode, but after build, they arent there
Why not just use GetAxis/GetAxisRaw instead of duplicating all this code?
it doesnt really matter tho
Start debugging
the computer hasnt registered it as a bug
What?
on my console, there isnt any red text
So you know what a bug is? The computer cannot recognize bugs
Those aren't bugs
Those are errors
Bugs are when your code doesn't behave as expected
Log statements
I have the follow code and for some reason the Debug is return null. Any ideas? ```cs
Test Something = Test.Testing();
public class Test : MonoBehaviour
{
public static Test Testing()
{
Test obj = new Test();
Debug.Log("Testing: " + obj);
return obj;
}
}
Is one easy way
You cannot create a MonoBehaviour with new()
alr thx
I see
Only with AddComponent or Instantiate
I thought it was working totally fine before.... oh well
Maybe before it wasn't a MonoBehaviour
dare me
(this is not an educational piece of code nobody please do this)
You shouldn't* and it won't do what you want*
Maybe I was using a class within a MonoBehaviour class
Anyways, the test is working now. This stumped me for a day. Thank you very much.
I'm following a tutorial and am slightly confused by the reason for having this instance variable and just noticed they used it to reference this script by doing DataPersistenceManager.instance. without actually making a reference and dragging it into a field in the inspector. how does this work?
like, this data persistence manager class isn't static so I don't get how it just knows which script to get the .instance from
As a first person movement playercam move by mouse and keyboard. do you that in the script start or update string? I think update because of the input that i do..
It's a static instance property referring to the single instance
This is quite standard for a singleton
As you can see the property is assigned in Awake
how do I know this is a singleton, I know I implemented destroying duplicates but I don't know what makes it a singleton
The very fact that you destroy potential duplicate classes ensures that there can only be one SINGLE instance
is that all that's needed for a singleton?
yes

A singleton is just a workaround of having a static reference (instance) to a non static class
don't overuse it or you will end up in Singleton hell which is not a nice place to be
xD thanks for the warning
Is anyone familiar with unity navmeshing? How bad is it and what is the best documentation resource available
It's actually very good when used correctly, the best docs are always the Unity ones and can be found here https://github.com/Unity-Technologies/NavMeshComponents/tree/master/Documentation
This is for the 'old' version btw but the docs are still relevant
Old version is better honestly
!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
firstly Start not start. Secondly you are almost there, save the return from the Getcomponent
not sure what save the return from the Getcomponent means, can you explain what that means?
SomeScript someScript = GetComponent<SomeScript>();
someScript is the returned value
hi I have a project for a game like papers please or potion craft but I it's really time restrained and i don't know what shoul i learn in order to make it, does someone know if unity has visual scripting and i I could make something with it? if not could someone help me with what I should learn in order to make it or if there was a website where I could find templte to follow?
@split sage btw your !ide is not configured correctly. You need to do that before you can get any more 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
Does anyone know how to make low poly water in unity? I feel like making it in Blender 3d and animating it, but the issue is the water needs to be endless.
this shows it is not
If you create a chunk of water that connects seamlessly to itself, you could just keep on spawning them in a certain radius around the player.
Otherwise, you'd need to think of some procedural generation method in unity.
What about external tools?
Edit->Preferences->External Tools
It shouldn't be vague to you, as it's one of the steps in the config guide.
Do i make it with a plane in unity or can i design/animate the water in Blender?
Which one? I gave 2 options.
The first one
The first one you can make however you like.
It's a runner game, so the water is meant to keep generating ahead
Create a procedural shader
If you manage to make it connect seamlessly, that is.
Yeah, shader is another option.
A more complicated approach though.
what about the dents in the water? this is how i made it in blender
You can add mesh variation using shader
One sec
Can i use the one I made in blender and export it?
Vertex displacement.
Yes, you can do whatever you want with a shader.
Given you know how to write/create it.
in my example I declare a variable named someScript of type SomeScript so the it can be filled by the return value of GetComponent which will be of type SomeScript. If this is not obvious to you I would suggest you follow some basic C# tutorials
Feels like you need to learn about types and objects.
I don’t think so, but there are Unity packages that you can use a template or just use them in your game. here’s a good low poly one https://assetstore.unity.com/packages/tools/particles-effects/lowpoly-water-107563 Here’s the one I use: https://assetstore.unity.com/packages/2d/textures-materials/water/simple-water-shader-urp-191449
ohh i see!
Microsoft C# beginners course.
And many other learning materials online.
That's a very subjective question.
btw there is no such thing as Unity C#. There is C# and there is the Unity API
The first one worked perfectly for me, however how do I make object float on the animation of the water?
Add a mesh collider i think
Did that, but it doesn't make the object animated with the waves.
That's a pretty complex thing to do. You can look up some tutorials on wave physics simulation.
or "water physics"
It seems rigidbody is the right way to do it
I think it's best if ijust animate the block instead
Absolutely. Simply reference the script, for example
public MyScript myScript;
And then in whatever function you want to change the value, type something like
myScript.valueToChange = 10
I animated a block, is it possible to make a character remain on the block as it's animated?
My character is stuck mid air when the block moves around
Could someone help me please? My character is supposed to remain on a block whom i have animated to rotate and move up and down a bit, my character remains on the block, but it doesn't follow the animation pattern of the block beneath it
I added box collision and rigidbody for both of them
I believe I found the issue, it's the collider that doesn't move with the block's animation :/
Hey everyone.
I am trying to make a camera thats inside a car.
You can move around the cursor and the camera will rotate to it but I also want the camera to rotate with the car if the car rotates so the camera follows that rotation and the movement of your cursor.
The camera is a child of the car.
camera script:
public float sensitivity = 2.0f;
private Vector2 rotation = Vector2.zero;
private Vector2 currentRotation;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
float mouseX = Input.GetAxis("Mouse X");
float mouseY = Input.GetAxis("Mouse Y");
currentRotation.x -= mouseY * sensitivity;
currentRotation.y += mouseX * sensitivity;
// Clamp the vertical rotation to limit it within a specific range (e.g., -90 to 90 degrees).
currentRotation.x = Mathf.Clamp(currentRotation.x, -90f, 90f);
// Apply the rotation to the camera.
transform.rotation = Quaternion.Euler(currentRotation.x, currentRotation.y, 0);
}
car script:
public Rigidbody rb;
public float baseSpeed = 17;
public float acceleration = 2.0f;
public float brakeDeceleration = 10.0f;
Vector3 rotationRight = new Vector3(0, 0, 30);
Vector3 rotationLeft = new Vector3(0, 0, -30);
Vector3 forward = new Vector3(0, 0, 1);
Vector3 backward = new Vector3(0, 0, -1);
private float currentSpeed = 0.0f;
void FixedUpdate()
{
if (Input.GetKey("w"))
{
currentSpeed += acceleration * Time.deltaTime;
}
else
{
currentSpeed -= acceleration * Time.deltaTime;
}
currentSpeed = Mathf.Clamp(currentSpeed, 0, baseSpeed);
transform.Translate(Vector3.down * currentSpeed * Time.deltaTime);
if (Input.GetKey("s"))
{
currentSpeed -= brakeDeceleration * Time.deltaTime;
}
if (Input.GetKey("d"))
{
Quaternion deltaRotationRight = Quaternion.Euler(rotationRight * Time.deltaTime);
rb.MoveRotation(rb.rotation * deltaRotationRight);
}
if (Input.GetKey("a"))
{
Quaternion deltaRotationLeft = Quaternion.Euler(rotationLeft * Time.deltaTime);
rb.MoveRotation(rb.rotation * deltaRotationLeft);
}
}
Because you need to replace “MyScript” with the name of the script you are referencing
Hello
I have a repository on Git, there is a template for working with plugins
and I used this template in the project
now I have slightly updated the template in the template repository
how to organize an update in the project turnip already
those. Is it possible to somehow make a quick update from one repository to another?
maybe I can somehow make a private package in my asset store, where you make updates, and via PM you update the version in projects
I would just give the camera a parent object and then make the parent objects rotation follow that of the car. Then, make your camera controller script change the local rotation of the child object
Use localRotation for the camera script not rotation
Oh true
praetor i see you everywhere
i was just looking at an online forum for help and you're just there
thank you 🙏
Why doesn't it trigger?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GateScript : MonoBehaviour
{
private WorldGenerationScript generationScript;
public void Inititialize(WorldGenerationScript generatorScript)
{
generationScript = generatorScript;
}
private void OnTriggerEnter(Collider other)
{
// generationScript.GenerateNewArea(transform.position);
print("hello");
}
}
it doesnt print "hello"
Could someone help me? My mesh from blender FBX exports the model horizontal, rather than vertical
A Rigidbody is required for OnTriggerEnter
not a code question
yes it works now thank you
ty, sorry bout that!
this is what happens if I change it to local rotation
just looks like you're rotating on a wrong axis
otherwise looks perfect
looks like you're rotating on the z axis
!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.
Because you never use it
You have to call the function, specifically: https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html
That method is inside OnTriggerEnter
Move it out
But you also have it embedded inside the OnTriggerFunction, but that's another issue.
If you call it. It wasn't activated by OnTriggerEnter the way you had it (as your warning told you)
its weird Cuz the Z axes is not assigned in my script.
and I changing my camera rotation in the inspector does not change anything
you'd have to show your code
here
you've put a function inside another function. As a beginner who isn't sure what's going on, you should avoid doing this at all costs. it will only bring you confusion
public float sensitivity = 2.0f;
private Vector2 currentRotation;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
// Get the mouse input for rotation.
float mouseX = Input.GetAxis("Mouse X");
float mouseY = Input.GetAxis("Mouse Y");
// Update the current rotation based on mouse input.
currentRotation.x -= mouseY * sensitivity;
currentRotation.y += mouseX * sensitivity;
// Apply the rotation to the camera.
transform.localRotation = Quaternion.Euler(currentRotation.x, currentRotation.y, 0);
}
can you show your car and camera objects in scene view, with Tool Handle Rotation set to "Local"?
is there a way to check if a coroutine is running in a if statement?
you shouldn't need to really
have you added additional logging?
Is Cancel running properly?
i was debugging my coroutine and i dont want PrimaryAttackInputCanceled to send a debug statement to my console when the coroutine isnt even running. it just makes it harder to debug
from what ive seen it seems like it
oh wait
StartCoroutine returns a Coroutine reference
actualy. when i was pressing and releasing the trigger rapidly it didn't execute once
yeah that's the issue then
you should turn Collapse OFF
so you can see the order in which these things happen
yeah that's your problem
your car is oriented completely wrong
blue is supposed to be forward
green is supposed to be up
You will need to go back to blender or whatever 3d modeling program and re-export it properly for Unity
Actually you can't use that reference to check if it's running on the mono strangely enough, but you can use it to stop it?
there's no built in way to check if a coroutine is still running
workarounds are to use your own bool or explicitly set the coroutine reference to null in all places where it might stop.
Yeah, it's odd you can remove it without having a method of checking beforehand.
its not just PrimaryAttackInputCanceled that isnt running. inputActionMap.Weapons.PrimaryAttack is not being canceled?
is it a problem with the input system?
its a scatchfab model I used 
Thanks for helping me!
@wintry quarry
Canceled probably won't run for the shoulder button until it's 100% released
Hey guys, if I am using a filler image for my exp bar. But every time I pass a level the amout i need to the next one is dif.. how does the threshold that is 0 - 1 knows exactly the % to show?
it doesn't know anything. You tell it what % to show as a portion from 0 to 1
your code will have to do the mapping from whatever your range is to the 0-1 range
yeah.. but how do I do that if all the level have dif amout of exp needed?
If you see that log message then everything else also happens. Unless you have an error.
With code?
What are you expecting to see that isn't happening?
float fillAmount = currentExp / neededExp;```
I am I am using like that.. but when I pass a level neve level it starts already in 50%
I mean it's all up to your code logic
do the math
Then currentExp is half of neededExp
So you need to fix that
Look at the line it tells you something is null on. Make that value not be null
exactly, but the prob is that the bar stays in 50% at start next level, and I want it to go to 0% .. and not being able to think about something how to fix it using the way I am like that: cs fillEXP.fillAmount = _player._playerAllTimeExp / _player._playerExpNextLevel;
Simple math, no?
Because it's not a compile error. It's a runtime error
prob but for a dumb guy in math like me .. its hard math
Then you will need to set _player._playerAllTimeExp back to 0
at least i know I was going to the correct way and will try to figure it out here, Thank you guys !!
float allTimeExp;
float nextLevelExp;
float prevLevelExp;
float fillAmount = (allTimeExp - prevLevelExp) / (nextLevelExp - prevLevelExp);```
hmm ok will check the logic and try it, thank you !!!!!
DM me if you want
Did you fix your error
Because right now it looks like you're trying to change variables of nothing
Then do that
Of what
What thing are you trying to change the variables of
Okay where do you reference that script
And where do you assign a value to that variable
I'm not sure why you're showing me this
Where do you assign a value to the myScript variable
So myScript is null
Which is why you get a null reference exception
Because you're referencing null
null does not have .gravity or .jumpPower
When i started my game, this error repeated on 100 times /per second
did ya read it?
yeah im confused tho, i watched some tutorials on how to remove it but everyone just waffles on something that isn't even relevant to the problem I have
I'm wondering if anyone here knows about it
All good. Do you understand what it means when something is "null"?
no
Ok. So the error you're getting is a NullReferenceException as you can see in the text above.
First read what that means: https://docs.unity3d.com/Manual/NullReferenceException.html
Yeah. So if you look at your error message, try to understand what it says. It's actually telling you where the error is happening. Let me know if you need help understanding it. But try to tell me where the error is.
the error is located on my LevelControl object
What script is on that object?
Something on line 13 of CollectableControl is null but you're trying to use it anyway
So look at that line and see what's null
oh cheers lol
I'm literally just repeating what the error says
I gave you no information the error didn't
But all good. Just was surprised that someone actually wanted to try to understand for once.
thanks tho, much appreciated
Specifically, make sure you understand this part:
It's telling you exactly where the error is. You will get this error A LOT. So it's good to understand.
I thought you were doing an excellent job of it as well, more people should try it
agreed
If you reference all of them individually
When you clone them, keep a reference in a list. Iterate that list and change them all individually
That should definitely be something you know how to do before touching unity. Take a beginner C# course to refresh yourself if needed
Is it possible to keep camera preview in the bottom right corner to constantly show when i'm moving around in the scene?
Why does the debug.log work but not the rest of my code? ```
public void Drop()
{
Debug.Log("Item Dropped");
int Default = LayerMask.NameToLayer("Default");
Item.layer = Default;
Item.transform.parent = null;
Item.transform.localScale = Itemscale;
RaycastHit hitDown;
Physics.Raycast(transform.position, -Vector3.up, out hitDown);
if(Item.transform.childCount > 0)
{
foreach (Transform e in Item.transform)
{
e.gameObject.layer = Default;
}
}
foreach (var c in Item.GetComponentsInChildren<Collider>()) if (c != null) c.enabled = true;
foreach (var r in Item.GetComponentsInChildren<Rigidbody>()) if (r != null) r.isKinematic = false;
}```
I'm also not getting any errors.
Well, you log the very start of the code. May want to add a few more further in the code.
Just because it doesn't throw errors doesn't mean your logic is correct.
ok
I put it at the very end and i'm still getting the log.
Nevermind apparently, its one of the objects in my scene, that wont let me drop it.
You've got like a lingering raycast in your code there which I'm not too sure of its purpose.
Oh yea, let me delete that.
Actually the real error, was i was changing the current held object in update constantly, which was causing me to not be able to drop my current object.
What made you think coroutines could only be started at the start of the game
So don't start a new one if it's already running
Have a boolean that you set when you start a coroutine, and don't start a new one if that bool is set
If I'm generating the C# class from input system, and instaniating it in Awake, I would assume best thing is to just make this a singleton? Because for example my PlayerController script will need input, but then my BoatController script will need input, etc.
Hey guys, If I make a math 12 - 10 and in debug view it shows me 1.8 what is wrong here?
One of the values is not what you think it is or you're looking at the wrong output
hmm well impossible. all the math is being done with whole numbers.. but well who knows thank you
That's what they always say
i amdoing actuall exp - expto next level.. and both are whole number haha
Are they both int variables?
no float for now
Debug.Log($"{exp} - {expToNextLevel} = {exp - expToNextLevel}"); and show what it prints. Use the actual variable names
For the value you want to be a while number do Mathf.RoundToInt(value)
Not a bad idea, but using a service locator pattern for it would be better probably
oo interesting
i feel like i've done something similar before when working with csv and excel files, but that was factory pattern.
It's just a minor thing if you decide to have like a local multiplayer or something you'd use that instead
I have an fps game so I move camera with mouse.How can I use cursor on UI with an input?
What is the specific problem you have? What is preventing you from doing that?
My cursor is locked and invisible
Unlock + make it visible when you open UI
okay thanks
Hey guys, how can I sort some gameobjetcs from closest to furthest from a point by using a script?
or use a modifier like some old games like tera, where you pressed alt to make the mouse visible again
I did something like that
[Array of Gameobjects].Sort(Vector3.Distance);
How can I stop the camera when cursor is visible?
Thanks
You could run the camera movement code in an if statement.
if (cursorIsVisible == false)
{
Move the camera;
}
Hey, sorry had that in mind wrong, here is better code:
GameObject[] arrayOfGameObjects;
arrayOfGameObjects.OrderBy(r => Vector3.Distance(point, r.transform.position));
point is your reference point
Oh okay thank you
Now I understand
You could also compare the sqrMagnitude to avoid a bunch of sqrt calls
how do i remove Z rotation from my gameobject
nvm found it
In code? Reference the Text as TMP_Text, then you can modify the text property on it
a public property on your class, so you can assign it in the inspector
like public TMP_Text YourText;
then you can do YourText.text = "hello world" later in your code
.text =
hey i am making my first unity project and currently having issues with my imported house that i made with blender. Is there anything i can do to stop the walls from being transparent after entering the house
sorry
Finish modelling the house
you did not model the interior
Hi. Is there a way to hide those events under a dropdown or a checkbox or whatever (it just ocuppies a lot of visual space for the script in the inspector)
either put them inside a class or struct that you serialize or you'll need to use some editor code like a custom property drawer or whatever
alternatively you could get an asset like NaughtyAttributes or OdinInspector which include some Foldout attributes
.ToString
I was already using the tetracreations attributes, would NaughtyAttributes work with the tetracreations one or they would try to overlap and break something?
i don't know. i've never even heard of that asset you are using
knowing how naughty attributes forces a custom inspector on all MonoBehaviours though, i imagine it won't work together with that other asset very well. however naughty attributes does have at least most of the attributes that other asset has
Tried looking up naughty attributes, is github having problems? I only get 404 for that repo
works for me 🤷♂️
https://github.com/dbrizov/NaughtyAttributes
oh well now it works again
tried the last 3 minutes, logging out and in and it only showed 404 😄
ToString returns the string. it doesn't magically convert that variable to a string in place
The first two lines are unnecessary
scoreText.text = score.ToString();
score += 1
yeah so is the scoreText.Text + on the third line
also if you want to display it with a specific precision you can use a format string inside of the ToString call
https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings
I often read about using interfaces as a good practise; still even though I already program for quite some time in unity, I very rarily find good use cases for interfaces, since my code worked just as well by just using concrete types or base classes. I know that I could add interfaces there as well, but to me this would just add an an unnecessary layer of abstraction. Is this normal in unity, or am I doing something wrong regarding my architecture?
honestly just use what makes sense to you. it can make sense to use interfaces, but that doesn't always mean they are necessary to use. a lot of the use cases for interfaces in unity can also just be a concrete class as a component. so just do whatever makes the most sense to you
for example, I personally like to use an IDamageable interface for objects that can take damage so that my types that deal damage can just use TryGetComponent(out IDamageable ...)
however this could easily just be achieved using a specific component that handles taking damage and applying it to a health component or whatever it needs to do
I see, I think I can grasp the use cases a lot better now, thank you!
Composition (adding components to do things) is a more Unity way to do things IMO
I.e. instead of making a Player script that is IDamageable, you just additionally attach a Damageable component to the player object
That also seams reasonable, thanks, I will keep that in mind as well.
You probably also want to add to the score before converting it to a string, not after
is there a way to have code that runs when an if statements check fails?
or something like that when a while loop breaks
look for "else"
im using an interface in the check so i needed the specific reference but i think i found a way round it
if (!condition)
Or else
Or just return in the if statement, so any code after only runs if the if statement failed
!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.
i explained the problem really bad my fault
i want the code to turn on a variable when the object is aimed at
but also turn off that variable when its not being aimed at
but i use an interface to reference the specific object that is being aimed at
so if the check to see if the interface is present on the component fails i cant edit the variable after the object stops being looked at
i had an idea that i could use a global variable to store the data of the last object with the interface and just update it through there if the check fails but i wanna see if theres any different ways
Save a reference to the object in a variable
- you don't want that while loop.
- use else
- check input in update
what's going on here?
i can fix the error by casting the entire thing to byte but i'm wondering why this is happening and if theres a cleaner solution
What line of code can you use to edit the rotation transform of an object?
transform.rotation = [value]
I've tried that, its telling me its incorrect.
What does the error say?
Hm, must be the operation I'm doing that's incorrect?
unity uses quaternions to represent rotations, which a quaternion / certain rotation can be represented using Euler angles which you are likely more familiar with (traditional 0-360 degree rotations). Use the Quaternion.Euler(x rotation, y rotation, z rotation) function to generate a quaternion/rotation with x y and z axis rotations
What about this?
ive personally never used the transform.Rotate() function
i think that has a similar effect to adding rotations like you were trying to do before
you usually store whatever rotation you're tracking as an external variable in degrees, then every frame in Update() setting transform.rotation to a new quaternion using that variable
bump
Why not just declare a byte and do some byte | anotherByte
Bit-shift operators return int, as numbers get large very fast with those
I thought thats what i was doing
so what does casting to byte do? just chop off all but 8 bits?
truncation
can you elaborate please
basically chop it off
Yep, but it also checks that the number is in range first, at compile-time
lol
im really interesting in preserving the first 6 bits so
sounds a little expensive
No? At compile-time
This will still return an int, but here you can safely cast to a byte since you'll always end up with a number that has less than 8 bits
yeah
Yeah about runtime with your first version, this will throw an exception if the value is out of range for a byte
currently just trying to figure out how to efficiently edit bits in a byte
Yup with |, &, and ~ (invert all bits)
Oh there's also ^ (exclusive-or), very useful if you need to toggle a specific bit on and off
so does this get automatically truncated at compile-time?
Well that's just 0
there's nothing to truncate
always stored as 00000000 in memory
At compile-time you'll get an error if the number is too large
Compiler is smart, and does static analysis of the number to see if it fits. Only works when the number is constant or known at compile-time like here
If you try to cast a number in a variable that's out-of-range, the compiler won't be able to check that, and you'll get an InvalidCastException at run-time
Compile-time error example (1 << 12 produces a 12-bit number, way above the 8 a byte can handle)
oooooooooooooooh
i was under the misconception that when i declated the byte with all those bits, it reserved that many bits in memory for the byte
was confused af
Nope, it's just how the number is written, determining the size is done afterwards
You can even format the numbers with a separator, if they get too hard to read!
const int OneBillion = 1_000_000_000;
Discord's syntax highlighter surely doesn't like that
anyone have any idea why physics are getting messed up when i build my game? they are moving way slower than normal
here is an example of the code
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.
because the movement code doesn't account for the frame rate
all of your movement is framerate dependent
oh i see how would i change that
You'll want to multiply any "speed" values by Time.deltaTime to get them in terms of units per second instead of units per frame
I see I will give that a try
so in that example i would change "boulderspeed" to "boulderspeed * time.deltatime"
does anyone know why the jumping part of this script doesnt work:
using UnityEngine;
public class Testing : MonoBehaviour
{
public CharacterController controller;
public Transform cam;
public float speed = 6f;
private float _turnSmoothVelocity;
private bool _groundedPlayer;
public float turnSmoothTime = 0.1f;
public float playerSpeed = 6.0f;
public float jumpHeight = 1.0f;
public float gravityValue = -9.81f;
private Transform _playerTransform;
private Vector3 _playerVelocity;
private void FixedUpdate()
{
_groundedPlayer = controller.isGrounded;
var horizontal = Input.GetAxisRaw("Horizontal");
var vertical = Input.GetAxisRaw("Vertical");
var direction = new Vector3(horizontal, 0f, vertical).normalized;
if (direction.magnitude >= 0.1f)
{
var targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
var angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref _turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
var moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDir.normalized * (speed * Time.fixedDeltaTime));
}
if (Input.GetButtonDown("Jump") && _groundedPlayer)
{
_playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
}
_playerVelocity.y += gravityValue * Time.fixedDeltaTime;
controller.Move(_playerVelocity * Time.fixedDeltaTime);
}
}
I made a new movement script that is better and then tried to transfer the jumping part of my old script to the new one and it didnt work.
you're using GetButtonDown inside of FixedUpdate. GetButtonDown will only return true the first frame the button is pressed which may not be a FixedUpdate frame
typically you would get input inside of Update to avoid issues like that, then apply physics inside of FixedUpdate
ok, ill try that.
it still doesn't work after changing to Update(), sometimes it barely jumps a little bit and other times it doesn't jump at all, and it only jumps a little bit if my character is moving. https://pastebin.com/jmVauW0E here is my old movement script where the jump works perfectly. Thanks for the help.
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.
if the jump is not strong enough then you need to increase your jumpHeight
@frank lightI've found CharacterController's isgrounded to be very wonky in the past. You might be better off doing your own overlap check
ive already tried this before.
well then what debugging steps have you taken? because there's nothing in the code you've shown that would inherently make the jumping not work
Ive tried it with the other script, changing values, writing to the console if grounded. I think Burt is correct because it only does a jump when i am moving which makes sense that it would be isgrounded being weird.
you're also multiplying by Time.fixedDeltaTime in a frame update loop
you should have debugs in your code to test if your jump code is firing
you also don't really need to do the square root thing for jumping.
find a comfortable value.
Hi, I am using the OnTriggerEnter2D to create usable powerups. The destroy ist always working but not the boolean assignment (at least not always).
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "powerup-small-car")
{
smallCar = true;
Destroy(collision.gameObject);
}
if (collision.gameObject.tag == "powerup-big-car")
{
bigCar = true;
Destroy(collision.gameObject);
}
}```
I would appreciate every idea on this 🙂
It seems to work every time if i wait long enougth between the TriggerEnter events..?
if the destroy fires, the bool assignment HAS to fire too, no way around it
use debug.logs to figure out if your if statements are actually firing
Could someone really quickly explain why when I set the animation it doesnt work and puts the zombie in a weird position?
Okay i will debug some more. Thank you guys
what does the animation step contain?
And what do you mean with weird position?
ill send a video
Yep. But you need to adjust the boulderspeed to account for that (make it 30-100x larger)
Because you are now multiplying it with a small value
To add to that, if you multiply a value by Time.deltaTime you reach the full value of your original value after one second (when summing all the values you get together)
Okay nvm. you are right. Looks like FixedUpdate() ist not liking my variable change
Be careful with fixedUpdate and update, update dependent actions could run multiple times between fixedupdates, so if you are resetting variables somewhere keep that into account
FixedUpdates will be most likely 60 times per second for you, if you get 600 fps you will have ~10 update cycles before another fixedupate
I am doing something like:
private void FixedUpdate()
{
if (smallCar)
{
Debug.Log("small");
scaleCar("small");
Invoke("setDefaults", powerUpTimer);
}
if (bigCar)
{
Debug.Log("big");
scaleCar("big");
Invoke("setDefaults", powerUpTimer);
}
}```
Inside the setDefaults i reset the booleans to false. Should work normally or? Right now i got no Update()
But doesn't it work? I put the variable of the Motion in there
Or am I meant to do the entire thing
In that case your fixedUpdate would run repeatedly until your setdefaults is executed
do you get multiple "small" logs before the values reset?
There is no logging at this point. Seems like the if does not hit
Yeah it doesn't work either way, I'm really trying to find this bug somewhere.
only the name is empty, look at his second screenshot, it shows a mixamo animation
afaik each animation state should be connected with an arrow somehow
maybe I'm wrong
yeah his entry state feeds into the empty state
Can you change FixedUpdate to update and see if anything happens?
That seems to work. 1 "small" log. But i don't understand why this work 😄 And i am scaling the GameObject (with physics). I think that's not good in the Update() method, right?
hi there! so ive hit a bit of a coding brick wall. how can i make it so that when i select a node which a tower is on, that it shows the range of said tower using a prefab object that is scaled to the turrets range?
https://hastebin.com/share/ebecurogit.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Can you show your full class?
Hmpf, debug is working but somethimes the scaling ist not working
Do you have an animator on the car object perhaps?
No, only Rigidbody 2d, Wheel Joints 2D, Box Collider and scripts
What's the issue again, is it that the scale just does not change sometimes?
In editor or in game?
At first the if inside the update method did not always hit. Changed FixedUpdate to Update and now this seems to work.
But the scaling is not working
in game.
Make a prefab that has a disc-shaped mesh and show that prefab on the selected tower
I hear your question but I don't know what issues you are facing
It could also be a plane/quad with a circular texture
i need it to also scale for the range of the currently selected tower. i got it to run without errors once but it didnt move or scale the range prefab
Can I add a strikethrough in a GUI button text?
Only alternative i could think of is to just change the color to orange-red for now.
https://i.imgur.com/oZcOuXS.png
although saying that....the towers are placed via the node...
You need to use a GUIStyle that has richText enabled
Moving/scaling a gameobject is really simple, maybe show the code you tried?
Perhaps you were scaling the prefab and not the instantiated object
https://youtu.be/S4W-QBpQgiU i was trying to follow it from this tutorial as there isnt a lot of 3d tower range tutorials
I just created anouther debug.log inside the scaleCar(). This is hitting exactly 1 time but no scale transformation is happening (on the secound trigger)
Alright but you need to be specific about the issues you are having
I still dont know exactly what went wrong when you tried it
nothing happened. thats the issue. i had some run ins with null but i fixed that easy
Lol, 'nothing happened' is even more vague than anything you said before
Nothing happened when doing what?
May be a bit confused but doesn't unity usually not support that for its regular GUI?
Or is there an easy way to add it if my specific line was something like:
DropObjects("Center", false);```
this
I think certain GUIStyles (like the one for button) does not have it enabled by default.
You can create a new GUIStyle with var guiStyle = new GUIStyle("Button") or something like that. I think "Button" converts to the basic button style
When resetting the bool inside the scale method it seems to work. I am quite not sure why i should use Update() and not FixedUpdate() there :3
So are you saying that transform.localScale is not working
and transform position.
Ok. You need to show what you tried
Like show the actual code that didn't work
the code mentioned in the youtube link i sent
that doesn't help anyone
No, the code you wrote
You are telling me to watch a 7 minute video just to see the code that you are supposed to use
You probably copied it wrong
I appreciate the help, sadly a bit out of my realm for right now until I have more time to look into it.
Just going to quickly comment out these 2 buttons until I have the time to get back to fixing them.
well its actually more two minutes for the actual code lol.
but this is what i tried
using UnityEngine;
using UnityEngine.UI;
public class NodeUI : MonoBehaviour
{
public GameObject UI;
public GameObject Range_indicator;
public Text towerStats;
public Text upgradeCost;
public Button upgradeButton;
public Text SellAmount;
public AudioClip upgradesfx;
public AudioClip sellsfx;
public AudioSource sfx;
public Node target;
void Start()
{
sfx = GetComponent<AudioSource>();
}
public void setTarget (Node _target)
{
target = _target;
//Range_indicator.SetActive(true);
//Range_indicator.transform.position = target.turret.transform.position;
//Range_indicator.transform.localScale = new Vector3(target.GetComponent<Turret>().Range, 1 , target.GetComponent<Turret>().Range) ;
transform.position = target.getBuildPos();
if (target.is_lvl_1)
{
upgradeCost.text = "MANA: " + target.turretBlueprint.upgradeCost;
upgradeButton.interactable = true;
}
else if (target.is_upgraded_lvl_2)
{
upgradeCost.text = "MANA: " + target.turretBlueprint.upgradeCost_lvl3;
upgradeButton.interactable = true;
}
else
{
upgradeCost.text = "MAX";
upgradeButton.interactable = false;
}
//sets the stats for each individual tower
towerStats.text = target.turretBlueprint.towerStat;
//updates the sell price for the selected turret
SellAmount.text = "Mana: " + target.turretBlueprint.GetSellAmount();
UI.SetActive(true);
}
public void Hide ()
{
UI.SetActive(false);
}
public void Upgrade ()
{
if (target.is_lvl_1 == true)
{
target.UpgradeTurret();
buildManager.instance.DeselectNode();
sfx.PlayOneShot(upgradesfx, 0.7F);
}
else if (target.is_upgraded_lvl_2 == true)
{
target.UpgradeTurret_lvl3();
buildManager.instance.DeselectNode();
sfx.PlayOneShot(upgradesfx, 0.7F);
}
}
public void Sell()
{
target.SellTurret();
buildManager.instance.DeselectNode();
target.is_Max_Upgraded = false;
sfx.PlayOneShot(sellsfx, 0.7F);
}
}
i would use hastebin but it says it would remove the current code saved which i sent earlier
well its actually more two minutes for the actual code lol.
Why didnt you just give a timestamp then? You gotta realize that people volunteer to help here and you should make helping you as easy as possible
i thought i did. sorry
Is Range_Indicator a prefab?
!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.
And yeah that ^ put your code in a paste site
yes
So it's not Instantiated anywhere?
i add it into the game out of view as well
A prefab does not exist in the scene
Can you show that code
Or do you mean you added it into the scene yourself, instead of instantiating it via code?
yes. added into the scene
Did you get errors while playing, with that code enabled?
yes the null errors but i fixed those. i cant find the code i used to fix the null errors however
Uncomment those lines, run the game, and check the console
The code related to Range_Indicator looks ok, so maybe you had some errors.
huh....odd
the range shows up now but the ui doesnt. so yeah. it seems the error is elsewhere
although it says the error lies at line 34
NullReferenceException: Object reference not set to an instance of an object
NodeUI.setTarget (Node _target) (at Assets/code/NodeUI.cs:34)
buildManager.SelectNode (Node node) (at Assets/code/buildManager.cs:46)
Node.OnMouseDown () (at Assets/code/Node.cs:52)
UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)
Why do you think it is elsewhere, it says the error is right there 😄
cause it also brings up the build manager.selectnode
Something on that line is null. It can't be Range_indicator because the lines above it used it and didn't throw an error.
It could be target or the Turret component on target that is null.
i was thinking target because its used to move the range as well as select the tower
Though if this line is not erroring Range_indicator.transform.position = target.turret.transform.position; then target can't be null
What is target.turret? Is it the Turret script or something else?
Everything hints at target.GetComponent<Turret> being null
i used target because in the video he seemed to use something similar. but it turns out i dont need that. it moves the range between turrets, but doesn't scale it. and the ui doesnt open still
it points to the node as well with the error
You know if a line of code gives you a NullRefException, any code below that line will not run
So you gotta fix those
You've got some nre
!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
If I am going to have several different objects that can be interacted with, but specifically for the UI element it will just be "Press E" when you get near any interactable item, should that be an interface, or a base class?
I feel like it's often we would jump towards interface, but since the definition would be the same each time (display "Press E"), does a class make more sense?
Interface for interactions, invoke event for UI
Ah. makes sense.
If I want to make World Space text, just scale the canvas by e.g. 0.01 to make it reasonable size? Otherwise my text is huge
Or is there a better method/component to get it to proper scale
Yeah, so generic event pop up for the UI element, and then define specifically what the interact() is from the interface.
if its a generic "E button" without need to specify what it is just yeah invoke the event from your interaction script
your UI can just listen to that 1 script's event
Yeah that makes sense, thanks.
i have 2 game objects
directly above eachother
but there have 2 different posisitions
keep in mind that the position you see in the inspector is the local position so it is relative to the object's parent
is there a way i can have a bool become automatically disabled if another of the same name becomes true or something?
i have quick bar slots that can become active to the players hand and each slot has a bool for being active
im wondering about a way to make a button click switch which slot is then active and disabling the last active slot
Use a world space text object instead of a canvas
Is that only for text or are there solutions for other ui elements too?
If you need other UI elements you'll need to use a world space canvas, but for text, a normal TextMeshPro object will do
thanks
also one more question, I put the rendering layer on my canvas on the highest sorting layer and it still shows the numbers behind the enemies running around, overlay camera or how do i solve that? 😄
just either store which was active and disable that, or disable them all and only enable the 1 newly active one.
alright thanks
is there a way i can check everything inside of an array and see which is a bool as true without using for?
foreach? why not using for?
i decided to use for
idk why i wasnt it just was feeling repetetive
for being repetitive is the reason it exists
I'm following this guide here to do a dependency injection, but I keep getting an error:
'GameObject' does not contain a definition for 'Initialize' and no accessible extension method 'Initialize' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)
It seems like I should be able to reference a game object though
the method Initialise is belong to your script not the gameobject, you have to reference the script (ie the component on the gameobject)
You notice how the prefab in that example is not of type GameObject
in a 3d top down game what do i do if the enemy is smaller then the player , cause my projectile is flying over the head of the enemy.
when I use transform.LookAt(Vector3.zero) , the player looks at the local 0,0,0 instead of the global origin. How can I fix this?
what is local 0, 0, 0? can you show a screenshot
I have the player starting at 0,-103, 0
and I want to use transform.LookAt to make the player always point at 0,0,0
im confused what part of this is your actual player, how can u tell that this circle is not rotating towards the correct position
the only thing I can think that RotateAround is affecting the rotation
https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html
This modifies both the position and the rotation of the transform
You could use only 1 rotate around call if you combine those vector3s and add the input. I would do it like
Vector3 rotateAxis = new Vector3(1, 1, 0).normalized;
void Update()
{
float rotateSpeed = //Do whatever you want here with forward and horizontal input;
transform.RotateAround(Vector3.zero, rotateAxis, rotateSpeed * Time.deltaTime);
}
and then afterwards call transform.LookAt if the rotate around part isnt sufficient
hey guys ive given my player the health script on the right and the slime enemies the hurt enemy script on the left
and for some reason when my character walks over and touches the slimes he takes 0 damage.
actually i just realised my player litterally walks over the slimes (both have 2D rigid bodies and 2D colliders)
did you debug if its ever calling HurtPlayer?
Couple things:
I wouldnt rely on the name of the player because this is fragile. you may want to do layer based collisions. If it somehow collides with another object named player, you now have a null reference exception error.
You dont need to check if the players health is 0 or below in update, since its only changing in the method HurtPlayer(), you can just check inside that method
Add debugs to see which part is wrong, if you arent getting the collision message, if its not entering the if statement, if damageToGive isnt 0
and follow the !code command for how to post 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.
whats wrong? it doesnt even change test value
thanks so much for this message
i actually am following a step by step guide on how to make a 2D rpg game but its 7 years old so theres a lot of outdated things ive had to fix and im guessing checking if the object is named player is one of them 🤣
how do i actually debug tho? like how can i check if its calling hurt player?
There is the debugger which you can attach and add breakpoints if you need detailed information and the game to pause. For something like this though I'd really just use Debug.Log and remove it when done
That guide probably isnt the best. A lot of guides only work the purpose of the video sadly and cannot be extended further
bawsi you seem like you know what ur doing in regards to making games what do you suggest I do to learn
ive been programming for a year now and I just thought following a guide was best to understand unity. is there a tutorial online u can suggest me?
The only real suggestion I have is just keep experimenting to learn. You can copy code all you want but it doesnt really teach you anything. In some cases like complex equations it's fine. If you truly want to understand what the code is doing, it's good to try writing it yourself and changing around values to see what effect this gives.
Hell, I was just doing this 5 minutes before I replied to you with a particle system and have a better understanding of them now
i see, that makes sense.
okay im gonna stop following this guide then honestly and just try to learn some basic unity syntax and make the game i want to
As for tutorials, I dont really watch many. Only for systems very specific to unity like the ai package or particle system.
Some tutorials for you though might give you more information and tell you about methods that you didnt know existed
You should really learn how to debug before you continue, itll improve your experience by a lot.
Forgot to @ respond on the message above
I see,
i guess i more want to know the functions and stuff that unity provides that I can use
like the debug stuff in unity.
somewhere on line 9 is referenced as null and i need to use parenthesis somehow but I'm confused where
!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
i already did like twice mate it ain't working
Then you've likely missed a step. It works, a ton of people here have followed the same guide. It's also a rule to have your ide configured to get help
what version are you using?
2022
hey i have 2 scripts("Ability" and "AbilityEvolveChecker"). How come im getting an error saying "AbilityEvolveChecker" namespace doesnt exist when i use it as a variable in the "Ability" script? I remade "AbilityEvolveChecker" with another name and that fixed it, but i kinda prefer "AbilityEvolveChecker".
Show the exact error message with an image
var floatyText = Instantiate(regenTextPrefab, floatyTextPosition, Quaternion.identity);
Why is this instantiating my prefab with a different scaling and position?
the prefab scale is 0.5 but the instantiated object scale is 0.2 (I'm not adjusting this anywhere in my code)
the position is the same as my floatyTextPosition but it adds some value to it that I don't add anywhere and are not in the prefab either
Log the scale for the prefab and instance and see if they're the same
ew it's my animation 😛
GetComponent<Rigidbody2D>().velocity = new Vector2(1.0f, 0.0f);
what valuse do new Vector2(1.0f, 0.0f) pass to the GetComponent<Rigidbody2D>().velocity
and if possible can i dont use new Vector2(1f, 0f); and just ype list (1f, 0f) with 2 variables kinda looks like no diffrence to me
It creates a new vector with the specified X/Y values.
You can absolutely pass variables for the X/Y values, instead of two number constants. But you need to keep the new Vector2 to instruct it to create a Vector2.
ok so if vector is just x and y values why do i have to create it instead of just passing them
.velocity = (1f, 0f); will NOT work because (a, b) is a Tuple, an entirely different type.
what is type of Vector
ok and ridgid body take the data of type of Vector 2 ok
The Rigidbody's velocity does
yes
Rigidbody is also a type itself
so i want to set velocity when i press space
void Update()
{
if(Input.GetKeyDown("space"))
{
GetComponent<Rigidbody2D>().velocity = new Vector2(0.0f, 1.0f);
}
}
to the object this script is attached to
What's the problem?
it does
Good! I'd use KeyCode.Space instead of a string for your GetKeyDown
i forgot about it
so this apply to the object the script is attached to if i wanted t move diffrent object how do i do it
do i set ridgid body to public and make it like variable
and then change it
Reference the other object
like i said here
ok
Hey trying to make a building system in unity but I am not sure on how to make ghost building follow mouse pos and have it so the actual building is placed there
I think there is a way to transform mouse pos into 3D coords, but you could always use a raycast, as for the ghost building you could just use the mesh with a semi-transparent material applied.
Lastly for the placement make it so that when mouse1 or whatever button you want is pressed spawn the selected model at the raycast’s position
Aye thanks
No problem
So it would be like on mouse click 1 instantaite object on hit point
For placing it
After getting the ray cast script above ect:
hello
if i wanted to ask a question should i just ask it here or should i make a new thread
This is the coding channel.
#854851968446365696 for suggestions on how to ask questions.
how i tried it with tags
here TankLight is name of script we try to change
why in code of the script Tank which is the main one
do we make another varaible
called the same as the name of the script
Hi. Is there a way to like make an attribute affect a bunch of variables at the same time? Like not having to manually write that attribute before every single variable
I'm not sure what you're saying but you'd create a variable to reference the component type you're wanting to reference.
is it obligatory
or can i just use TankLight the name of the script
I'm not sure what you're saying but this is C# basics for class variables (instances)
Make sure the button is under a Canvas. Make sure you haven't got rid of the "Event System" object in the scene (it's the one which relays UI events to your UI elements). Make sure nothing is in front of the button, that could block events from reaching it.
this dude said quote "we're ganna take the name of the script TankLight and name it tanklight" why do you name something that already has a name if this naming is obligatory then i go learn c#. it sound like it makes things more complicated with no reason
Nope! You'll have to put one for each targeted element
well okay thanks
The first refers to the type, the second with camelcase would be how you're wanting to refer to it in this script.
Make sure to check out the Unity !Learn tutorials or other tutorials pinned on this channel.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
int i = 42;
Type name (the shape of the box), variable name (the box itself), = value (what you put in the box)
i go outside
Internal Unity error, you can ignore this one
When none of the stack trace elements point to your own code, ignore
Hey guys.. To access and make active the LevelUpScrenn I am using cs levelUpScreen.SetActive(true); And it is working fine. But if instead I want to access a child and make active just 1 of its child. How can I access it? I tried cs levelUpScreen.GainAttackSpeed.SetActive(true); But that doesnt work
for instand the gainAttackSpeed
If it's parents are inactive then the child will also be inactive. You'll need to either change it's parent or make the levelUpScreen active and the other things in it inactive or some other way like that probably
Ok thank you
Hey how do I rotate the camera around the player with the mouse/gamepad using unity's input system?
How do i fix this? None of the solutions ive found on the internet has worked
I tried to google it
How can I disable "Reloading script assemblies" after every script change?
I don’t think you can, it reloads it when you make a change to your code
Edit -> Preferences -> Asset Pipeline -> Auto Refresh -> Disabled
You have to manually refresh when you want changes to take effect, ctrl+R.
Ahh excellent, cheers!
you can also split your scripts into multiple assemblies, then only the scripts inside the assembly that got changed need to be recompiled
when i have instanciated a prefab. How do i access a variable within its attached script?
how do I create a physical button that can be pressed? I've searched everywhere and I can't find one
What's the name of the script?
NPCBall
A UI button?
No a button you press with a keybind
I'm not quite following. Please provide more information if you want my assistance(:
A physical button, in the world
yes
You need a script on the player that will detect whether it's looking at a button, and a script on the button itself to trigger things when it's pressed
mkay
You can also skip a step and make RealBall of type NPCBall and then use:
NPCBall ball = Instantiate(realBall);
ball.someVariable = 10;
when i say
int a; int is type and it is needed as it passes some information for example type of variable a
the capitalized TankLight is name of script
in code TankLight tanklight
tanklight has a type of file TankLight
what does it mean something has a type of the file "TankLight.cs"
what information does it says about the variable tanklight
also later in code
tanklight = getcomponent<TankLight>(); guy explains this code finds the script in object components and i understand this so what was TankLight needed for at the beggining
It's not about files, it's about classes. When you refer to TankLight, in this case it will try to find where a class TankLight is located
A variable needs a type. You have to declare what kind of data a variable can hold
guy said filename but i was also thinking class has the same name as file
A variable of type TankLight can hold an instance of TankLight
and the name TankLight is name of the script or class in it
The file thing is purely a Unity thing for its internal purposes
In Unity it has to in most cases, but it definitely searches for a class name
As you can put multiple type declarations in a single file
Unity requires that component classes have the same name as the file they're in, but that's not a C# thing
The class name is what determines the type
ok
also when i work with velocity and use new vector should i like care that i make new vector every frame or it doesnt matter
Doesn't matter
It actually makes two vectors in your case. One when you use new Vector2() on it, and a second when it gets put into .velocity (the value gets copied)
GameObject redbird = GameObject.FindWithTag("second");
redbird.GetComponent<Rigidbody2D>().velocity = new Vector2(0f, 3f);
ok so i made 2 birds one was jumping ok and i tried to make second one jump using the script in the firs one so i tried something like this and now nither of them jump
i did put tag in redbird called second
You'd usually attach the script to the two birds separately
yes but for example when i kick the ball i think i could apply some velocity to the ball and not make a second script checking every frame has the abll been touched
so i just wanted to move other object without the script
Don't use find. Make public or serialized variable and drag in the object you want to reference
Code is probably not doing what you intended to, here in your deleted screenshot lol
Without braces, if statements only apply to the next line, so the second velocity you apply on the other object will always run
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
GetComponent<Rigidbody2D>().velocity = new Vector2(0f, 5f);//here the bird with code jumps
redbird.GetComponent<Rigidbody2D>().velocity = new Vector2(0f, 3f);//here i tried to make the second one jump too
}
if (something)
Debug.Log("Inside if statement");
Debug.Log("Outside if statement");
- Without curly braces your if statement applies only to the next line
- If the intention is to have both birds jump when you hit space then why are you making one script reference both instead of just putting this script on both birds
GameObject redbird = GameObject.FindWithTag("second"); how do you get the object
for example i have button to push somethign in game
and when i aim at something and push i want to change it's velocity
so i want to take the other object and change its velocity even if it doesnt have a script
i am just testing it on this
That's entirely different to what you've shown here, it doesn't talk about birds anymore
You're diverging
If you have a button that makes both birds jump then this script should be on the button and reference both birds
i wanted to move object with script in diffrent object
that's waht i wanted
my question was unclear
for example bird2 doesnt have a script and bird 1 have
so i want to move bird2 with script from diffrent object(bird1)
but it can as well be player and ball
Why doesn't it have the same script bird 1 does
If they're doing the same thing they should have the same script
lets talk diffrent game
i am first person player
and there is ball
and i can press lmb to push it
so i apply velocity to the ball
and ball doesnt have script
i want to move object with script in diffrent object
i simply already had 2 birds
so i was just testing
Then yes, you can get the rigidbody component from it and add force or set the velocity of it. I'm assuming you'd be getting the reference to the object from a raycast to determine if you've clicked on it
i am currently at trying to change diffrent object velocity
redbird have tag "second"
so i tired to find object with tag second
and then use it as if it was class with data
It is a class with data. It's a reference to a game object
FindGameObjectWithTag is not allowed to be called from a MonoBehaviour
what's the chance of 2 of this Random.Range(-2147483646, 2147483646) be equal?
So low that you can consider it impossible
Very low
i plan an intentional bug that can happen very low chance
It's lower than very low.
So decide on a chance first then make a random that rolls it
i dont want to actually trigger the bug, but i am expecting the bug to happen when two of this random is equal
With ideal probabilities, around 0.0000000233% for your current parameters
Wait no, even lower than that
It's (1 / uint.MaxValue) * (1 / uint.MaxValue) to get it twice in a row
Calculator probably won't be precise enough to compute it properly
5.42e-20 (542 with 20 zeroes before the decimal separator)
ig that's pretty good enough for me
If this is what you want it's probably easier to just not code in the thing at all and just tell people you did. It'd be basically the same functionality
it's just for an id system anyways, and the worst case that can happen is player can duplicate one item hehe
There's Guid which probably has even lower chances of rolling the same ID twice
Since it's on uh 32 bytes?
16* bytes
(for reference, int is on 4 bytes)
how
Make a prefab... here goes the message deletions again lol
ye i thought i should know this
and later if i dont get something ask
how to make a prefab
can someone help me? I have a boolean to check if the player is on the ground and it is working fine but the jump isn't working
Is the code in the second if statement running? Place a Debug.Log in it to make sure
"isn't working" doesn't help us help you
well when i put in a debug.log into the jump thingy it showeed when i pressed space but my character didnt actually jump
what does your character do when you press space?
First things first, you don't multiply by Delta Time here
oh well its working
It divides the force being applied by a factor of 100 (as it's around 0.016 at 60 FPS)
Also, presuming this is in Update, using GetKey is gonna spam the Jump
float x = 11;
void Update()
{
x = x-0.1f;
transform.position = new Vector2(x, -5)*Time.deltaTime;
}
block moves to the middle and shakes
i wanted it to smothly move from right to left
i deleted Time.deltatime and it started working normaly why
x = x-1f * Time.deltaTime;
transform.position = new Vector2(x, -5);
ok it works now
Might be an obvious answer, and im aware the fix is assigning the object that has the textmesh component to the feild. But it keeps reseting no matter what i do, like before I press play it is assigned but as soon as the game starts the feild becomes empty
Also forgive my code haha I am just starting to try and get to grips with this stuff
I have to keep dragging the object there everytime I start the game then it works fine
Hi friends, in code I am using this posX and posY to position my image, changing its position as I want. BUT it seems that this is not the real position.. how can I know the real one, because it is not appearing where it should.when i start the game and it appear apear almost outside the window
Because of your code in Start
Even if the counter jumps by 2 haha
Oh should it be in update?
No...
It should be deleted
If you want to assign the reference in the inspector stop assigning it in code
I think either transform.localPosition or GetComponent<RectTransform>().anchoredPosition
I am getting it like that cs Image GainMovementSpeed = Buttons.transform.Find("GainMovementSpeed").GetComponent<Image>(); and I am change its position like that: ```cs
Transform gainAttackSpeedT = gainAttackSpeed.transform;
gainAttackSpeedT.position = firstRow;
firstRow is using those values
but it is appearing outside the window almost
and not in the center as I see in the UI view on the scene
almost outaide the window when it appears
RectTransform uses anchoredPosition
and how do I get the values for anchoredposition?
or how do I fix that?
The same way as everything else
get the RectTransform component and access .anchoredPosition
and ui elements depend on your screen size. I recommend you solve this in a different way, for example with Layout Group Components. Moving UI elements via code is almost always gonna cause problems
Those are canvas space values. . position is completely the wrong thing
Hi, I'm using the free first person character controller, and I'm not sure how to reference this script from another script. I don't know how to use it's assembly in my own namespaced code.
Namespaces have nothing to do with assemblies
Ohh ok
If you're not using an assembly definition in your code you can just directly use this
I'm using an assembly definition in my custom code
Then you need to add their assembly as a dependency in your assembly
Assuming they have an assembly
If not you need to create one for them
Ah ok
Why would you be searching for days lol
I spend about a couple days a week doing game dev
Just look for the asmdef in their code
My time spent doing this was looking for this asssembly defintiion and trying other techniques
@wintry quarry Would this be the assembly?
Anyone know why mu jump count is registering 2 jumps when a single jump happens?
One second
how are you registering jumps?
Whats the best way to send code here?
!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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Ah thanks dude
GetKeyDown only triggers the first frame after a key was pressed
All clones of what?
Also one thing i noticed, why are you setting the velocity twice in FixedUpdate?
Thats a good point I have no clue why thats there twice haha didn't even notice
How are you creating these clones?
Best would be to keep a HashSet of all you create and iterate over that to delete them
This fixes that issue but now it seems to not register the space presses properly. It does it once or twice if im lucky
Ill figure it out eventually haha
You press it, release it and press it again and second time it does not register?
Yea
how do i install the new unity input system?
Then keep a HashSet (basically an unordered List) of them, you can do a foreach on it and destroy them
Like it only registers some of the presses
Via their package manager
how are you checking if it registered the press?
I think I figure out the issue its the else statement conflicting possibly
where?
https://img.sidia.net/ZEyI5/tEDezOte75.png/raw at the top choose Unity Registries (I have 1.8.0 installed which is a preview, you will have 1.7.x)
oh ok ty very much
Im using a bool that keeps track if the button is pressed or not which im guessing wont work well with GetKeyDown?
Should work with bool, check directly in the update function by logging
If you want it to be true while the button is held down then a simple yourBoolean = Input.GetKey(whatever); will do the trick
OnCollisionstay is not a good function to check if you want to jump though
you should save in a property if you are grounded and execute the jump in update if pressed + grounded
Got it!
what you typed is what a for loop does
Now do a for loop that has its value incremented by 3 each iteration
Yeah, type "for" then Tab twice
But yeah it's "complex syntax" that allows you to do way more stuff, like creating multiple variables before the first ;, put multiple conditions in the middle, etc.
used like that and worked now. thank you cs RectTransform gainMovementSpeedT = GainMovementSpeed.rectTransform; gainMovementSpeedT.position = firstRow;
Is there any way to make it shorter?
maybe put keycodes inside an array?
Alpha[1, 2, 3]?
idk if alphaX is continue, if yes:
for(int i=0;i<3;i++){
if(keydown(alpha1+i))number=i;
}
check it before use it
It works, but I don't really understand how, I would be happy if someone could explain it to me.
it shouild be number = i+1 to produce the same result you had above
public KeyCode[] keys = new KeyCode[3]
{
KeyCode.Alpha1,KeyCode.Alpha2,KeyCode.Alpha3
};``````cs
if (Input.anyKeyDown)
{
for (int i = 0; i < keys.Length; i++)
{
if (Input.GetKeyDown(keys[i]))
{
number = i + 1;
break;
}
}
}```
my bad
oh ya this works too. 😛 mine is just incase u want more than 3 I suppose
Thanks, I don't understand how "for" understands which key I pressed. But it works.
for isn't the one that checks the key
I understand that
the first solution is a bit frail(depends on magic numbers kinda)
but it works fine
Keycode.Alpha1 = 49
KeyCode.Alpha1 + i (1) = 50 aka Alpha2
so on
Hey guys, I just asked that question some minutes ago and I thought I fixed it but it seems not to be working still.
I am trying to change the posX and posY but it is not working. I am doing like that:
Vector3 firstRow = new Vector3(-10, 10, 0);
Image gainAttackSpeed = Buttons.transform.Find("GainAttackSpeed").GetComponent<Image>();
RectTransform gainAttackSpeedT = gainAttackSpeed.rectTransform;
gainAttackSpeedT.anchoredPosition = firstRow; ```
What I am doing wrong? Or what is a better way to change its position? When The player gain 1 level appear that button and it should appear in the middle of the screen.
KeyCode is just an enum, which is basically an integer number, you can see the list here https://docs.unity3d.com/ScriptReference/KeyCode.html
As you see the keycodes are listed in order, so doing Alpha1 + 1 will give you the number that corresponds to Alpha2
Oh looks like navarone explained it
Ok steps for that should be:
- create a parent "holder" in your level up screen
- create the movespeed button and set its parent to your "holder"
If you want multiple make your holder a vertical group
@solemn fractal
I already understood, thank
So what you mean is craete an empty object and make the button a child of this object, and I would control the position of the emptyobject and not the button it self?
yeah make an empty object where your button should be
that already exists in the level up screen
hmmm ok, make sense. Will try that. Thank you !!
and like i said, if you want multiple buttons add a Vertical Layout Group component to your "holder" and the buttons will list themselves up automatically
hmm vertical layout.. never did that will do a research about it, because I will have like at least 20 buttons. but they will appear basically in 3 position always.. randomly.. so I need to have those 3 position set
yeah then its perfect for you
why is it black?
Screenshots:
- unity
- blender
- blender
- texture
- alpha texture
not related to each other
not a code question here.
I imported it from the asset store. Do you know what i need to do?
not a code question
also not related warning to ur issue
Which channel do i need to put it?
oh sorry
#🏃┃animation or #💻┃unity-talk
describe clearly whats happening instead
are you using URP? if so i can help you in #archived-urp
Anyone know why the bools in my project aren't working at all trying to get a jump system working
Sending a video for reference
Ill send the code now too
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Because your code is changing them jump = Input.GetKeyDown(KeyCode.Space);
Jump turns to false the next frame because space is not being pressed
isnt that what he wants?
🤷♂️
just execute the jump method once on press
Probably just wanted to test it by clicking on the inspector but it doesn't really work here
oh wait, didnt see that in the video
Same with isGrounded
The jump also disregards the fact that im not on the ground and still works haha
Ohhh
Right
something wrong with these animations? because even when i try previewing it it doesnt work
how are you trying to preview them?
clicking then in the bottom right it should show but its not, i dont even care about that sometimes it shows but makes the zombie do nothing
double click on the node and at the inspector bottom right you should see the preview, if not then you might need to open it
I think you also need to have an object selected, which uses an animator with that controller
i tried but when i opened it it always says 3d model cannot be viewed or something
So what should I do about this?