#💻┃code-beginner
1 messages · Page 104 of 1
📃 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 didin't put it in Start
so why would it log when you start the game?
read the docs on how to trigger the OnTriggerEnter
omg
man
i added rigidbody to book and now it says wassup
tysm for helping me man
no problem
@rare basin you mentioned serialisable dictionaries earlier, how can i do that?
iterate over a list and insert it into a dictionary
and when you want to serialize it then you do the same backwards
rather a list of structs that holds tuples couples a kvp
something like that
i use GenericDictionary from github
free license to use in commercial
i ended up just making my own class which accomplishes the same thing
this is how i've done it at least
do you think this looks good?
in terms of item data
i dont know what do you want to achieve, but dictioanry would look much better ;p
what if you require X items in order to craft another?
you can do List<ItemData> craftWith
or with Dictionaries you can just do Dictionary<ItemData, List<ItemData>>
where the key is the item you wil lcraft, and value will be list of required items for it
i showed you how to share code 4 times
i wont help you if you dont adapt to the rules
you don't even nuderstand
what am i saying to you
if you will keep posting code as a screenshots
i wont help you
bro i made what you said i am asking another thing
read again what am i saying
this will never work, you cannot have 2 tags on 1 object
the if will never be true
yea i was trying to ask that
like what can i use
i want if this 2 book colides
destroy the gate
i have no idea what is gate what is book
theese are the bokes
if i press e they go back and touch the trigger
its like puzzle
oh lol sorry man
i tought you was saying about the old codes is the same as this you was talking about another thing
ok i will use the other sharing methods
those are some fat books
Are those books real 😂 ??
I'd love to read a book on wrestling 23
sounds like you're approaching it completely wrong then
You can still make an actual dictionary and when you Start() you just feed in the values into it then use that for the lookup
What they're saying is don't post screenshots of your code
yy i understand know
Hey, guys! I am dealing with a problem here. I am making pause and unpause functionality and for one reason only pause works and it not unpauses, I have used Time.timescale for both cases?
{
if (Input.GetKeyDown(KeyCode.Escape))
{
if (pauseIsActive)
{
StartCoroutine(ResumeAfterDelay());
}
else
{
StartCoroutine(PauseAfterDelay());
}
}
}
IEnumerator ResumeAfterDelay()
{
yield return new WaitForSeconds(pauseMenuScreenDelay);
pauseIsActive = false;
pauseMenuScreen.SetActive(false);
Time.timeScale = 1f;
Debug.Log("Pause menu screen is disabled after delay!");
}
IEnumerator PauseAfterDelay()
{
yield return new WaitForSeconds(pauseMenuScreenDelay);
pauseIsActive = true;
pauseMenuScreen.SetActive(true);
Time.timeScale = 0f;
Debug.Log("Pause menu screen is enabled after delay!");
}```
So, with couroutine how to make it work it is my first time dealing with that I mean in pausing and unpausing with coroutines?
Look into unscaled time
How to look? Is there a function?
i sent you a link. I suggest you learn something to help yourself
#💻┃unity-talk message
@timber tide Do I have to make that on the same method or do I have to change and make another one?
but i dont have this
i have this
replace your time methods with those
Leszek your character controller and ground check are not assigned. You need to follow the link sent to you about variables and the inspector assignments.
are you trolling ?
It is still a transform 🤷♂️
But looks like that is just a .... different script. Why is it relevant here?
are you just geniunly skimming through shit not reading ...
nah they were sent this link
https://docs.unity3d.com/Manual/VariablesAndTheInspector.html
and they don't understand what the variable they wrote is even doing or what they need to do
i suspect they read 0 of it
where would i put the dictionary?
Object reference fields
As well as bool, string, and numeric fields, you can also make any field whose type inherits from UnityEngine.Object editable in the inspector. This includes all built-in component types (such as Transform, AudioSource, Camera, Light), your own MonoBehaviour script types, and many asset types.This allows you to make use of the Unity Editor’s powerful drag-and-drop system in your own scripted components. For example, if you create a public Transform field in your script and add it to one GameObject, you can then drag another GameObject into that field in the inspector to set up a reference to that GameObject’s Transform component
, which you can then access at run time in your script. @wind meteor
maybe if i give you a snippet you will read it
i am tryin to get the 2d character to face the platforms surrounding him but it doesn't seem to face it and faces a different place
wait
let me fix it
!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.
anyone know how can i send my code like this
It's shown in the message right above you
It is not single apostrophes
It is a backtick, which on my keyboard is to the left of the 1 key
Maybe that was the issue?
You can keep it in the SO, assuming this is a unique SO (you've only one of these item data profiles per game, well it actually should be fine either way but it would make more sense to keep this unique).
i am tryin to get the 2d character to face the platforms surrounding him but it doesn't seem to face it and faces a different place
Just copy and paste this and replace "//code"
//code
No, copy the message I sent
It is three
In their own lines
Did you literally copy paste the formatted message or are you typing it? Not sure what is going on here
No. That copies the contents only
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GateOpen : MonoBehaviour
{
public GameObject Gate;
void Start()
{
Debug.Log("hi");
}
private void OnTriggerEnter(Collider other)
{
Debug.Log("hi wassup");
if (other.gameObject.tag == "first" && other.gameObject.tag == "second")
{
Debug.Log("aaa");
Destroy(Gate);
}
}
}
What if I want to use UGUI's Mask, but I don't want to parent the Mask Gameobject to the Gameobject being Masked?
Why is this code not unloading the loaded scene? ```
IEnumerator UnloadLevelAsync()
{
Progress = SceneManager.UnloadSceneAsync("1.0 Loading");
yield return null;
}```
i would first check if the scene with that name is active and also i would do something like this for debugging
var unloadScene = SceneManager.UnloadSceneAsync("MyScene");
while (!unloadScene.isDone)
{
yield return null;
}
Debug.Log("unloaded");
Okay
I dont know what key i pressed by accident, my scene is full white everything except the game
try to zoom out? did you hit the F key possibly ?
Yup it was the F key 😅 thx cheers
seeking help for implementing animations and states into my code
how can i change the model that the guy is holding in code?
is the model he's holding PART of the character mesh or a child object?
its a child
you can use this code i made for my project a while ago, it works by swapping two objects
using UnityEngine;
public class ModelSwitcher : MonoBehaviour
{
public GameObject modelA;
public GameObject modelB;
// Called when you want to switch the model
public void SwitchModel()
{
// If modelA is active, deactivate it and activate modelB
if (modelA.activeSelf)
{
modelA.SetActive(false);
modelB.SetActive(true);
}
// Otherwise, deactivate modelB and activate modelA
else
{
modelA.SetActive(true);
modelB.SetActive(false);
}
}
}
ModelA and ModelB should be your models
Attach this script to an empty GameObject in your scene.
Assign the modelA and modelB GameObjects to the respective fields in the script using the Unity Inspector.
Call the SwitchModel method from your code whenever you want to swap between the two models. You can do this in response to user input, events, or any other trigger in your game.
the second model will be replaced at the same coorinates and angle as the character's child
you can just do it much easier
Probably AI-generated
public class ModelSwitcher : MonoBehaviour
{
public GameObject modelA;
public GameObject modelB;
public void SwitchModel()
{
modelA.SetActive(!modelA.activeSelf);
modelB.SetActive(!modelB.activeSelf);
}
}
yea probably, the comments are weird, looks like chat-gpt 😄
And the instructions below, the way they're formatted
yea lmao
looks cool but what if i have multiple models
Use an array, and use the index to set one to true while setting all others to false
or List, if you want to add/remove to it during runtime
even better, events
i didnt realise it would be so hard to change the model
just a matter of approach
it is not hard at all
what exactly do you want to do?
sorry I didn't follow previous talk
I just wanna change the model, basically with the items i just wanna change the itemdata and when the itemdata is changed the model changes too
oww you are the craft guy 😄
so I assume you want to change the model when you "craft" new item?
yeah basically
i'd redesign it a bit
in the item class it turns the class into an actual dictionary
to as I said, serializable dictionary (no this is not a dictionary you mate)
and as a value have a serializable class
CraftOutput
where you have craftInto variable (the item that will be crafted)
reference to the new model
and needed items to craft it
then after crafting, access that new model and replace it
here i make it an actual dictionary
make it <ItemData, CraftOutput>
where CraftOutput is your serialized class
where you store as i said
required items to craft it, model to swap after crafting
public class CraftOutput
{
public List<ItemData> requiredItems;
/// other code like mesh to replace etc
}
but again without serializable dicitionaries this isn't possible to do (easily)
Really you only need lists to serialize stuff
what does craftoutput do
dictionary is for lookups
well for each item
you have ItemData right
and that ItemData has a dictionary
where the dictionary is a list of craftable items
I mean it's convenient to have a serialize dictionary, but the only thing serialize dictionary does is do 1 less step for you and it's loading the dictionary in start
in the dictionary as a key you put a craftable item
in the value you put required items, model to swap (CraftOutput)
i see
i'll have a go at my idea first
i just wanted to know how to swap my model because i have an idea on how i'm making this
it's a fine model, you've 1 item to a struct of item(s)
if that's what I think you're trying to accomplish
your key being the item type, and the struct are the values you need to construct the item
oh, for some reason I thought item data was a table of items, but if it's per item then you want to create the dictionary outside like an ItemManager class which you'd load into
i could just change the mesh filter right?
ye
whats the difference between the filter and the renderer?
A mesh filter is one way to provide a mesh for a mesh renderer to display.
The other source I'm aware of is a https://docs.unity3d.com/ScriptReference/TextMesh.html
(hence TextMeshPro's name!)
MeshCollider also looks for a MeshFilter to figure out what shape the collider should have.
That's why MeshFilter is a separate thing -- many things might need to reference the same mesh
this isn't a very clear explanation
"Mesh filter is the form of an object on the screen. While Mesh Renderer is the way it will look like on the screen."
I guess it's halfway there
MeshFilter provides a mesh. MeshRenderer displays a mesh.
i see why TextMeshPro was so popular
idk it made sense to me. Since the filter always has the shape inside of it
To be fair, you could make the text look good. It just took some settings tweaking iirc.
I use legacy for world text with shaders and it's aight
Has anyone else been having issues with TextMeshPro just showing up as invisible or giant black squares in the viewport/game view, but being perfectly fine in the scene view?
Cuz I've tried everything, including just using the default fonts provided by TMPro, but it just doesn't seem to work properly in game-view
Game view (left), scene view (right)
hey to make variables persistent across scenes what do you do?
is it as simple as making them static variables or adding a don't destroy on load?
or is it more case by case?
static or singleton
How do I set a rotation of an gameobject (an image in the canvas) to a certain value?
static exists throughout all scenes, while singletons you can manage their lifetime + some extra benefits
Also, is this the right place for this question, or would I want to put it somewhere else? I haven't really asked about much in this Discord and am unsure
https://docs.unity3d.com/ScriptReference/Transform.Rotate.html should work on UI actually
or just do .localRotation = Quaternion.Euler(
you dont want to set the rotation directly, it is a quaternion which is xyzw values and not what you expect. Use the euler versions if you want to directly set it to something
maybe #💻┃unity-talk , this is a coding channel. I assume your issue is that the objects are behind the camera
this set the rotation to 180 when I gave the value of 45...
thats not what i wrote
that is not a valid quaternion
Also, you wouldn't want to be modifying the return value of a value type from a property https://unity.huh.how/compiler-errors/cs1612
Im using input.getkey and I could not find any way to make it detect when I input space bar.
Please help thanks
https://docs.unity3d.com/ScriptReference/KeyCode.html
should just be Space
Idk if this technically would go under code but can I have something that replaces textures where a raycast hits? Like a bullet hole decal but rather than being overlayed on top of the object it replaces it. So that if part of the bullet hole is transparent you can see through it into the object.
thx have a great day
you could potentially modify the original texture/ material to add dynamic alpha map
not trivial probably
Ok thanks I'll try looking into that
hey guys is there a way to make this code shorter? https://paste.ofcode.org/aaELXNmapzV5ZuPdXyFqEh
if the values increase the same amount and also if they dont increase the same amount
start with a loop and make a pattern for increase rates ( maybe animation curve)
If each line progresses by a constant number, you just just do a loop.
But the pattern keeps breaking here and there.
Use a collection to store the values and increase each using a formula or a curve . . .
hmmm never heard of those terms.. collection and curve.. will check iut out
thank you guys
Use span. 
A collection is like an array, list, etc . . .
ohh, ok ok. got it, I think I saw that when I did a bootcamp. didnt remeber about it, will check it better thank you guys
You're confusing them
A collection is just any form of array or list
Dictionary, queue, etc...
Also, if the numbers don't follow a pattern, you can store them in teo separate arrays and just loop depending on the condition (if statement) . . .
That would be too much for them, for right now . . .
Them is a way to refer to a person.
It's a way to refer to someone without knowing how to properly address them. It's neutral . . .
what? what do u mean? didnt something change in the grammar? sorry I am not english native speaker
ohhhhhh ok ok sorry, i know what u mean now
ok thank you guys..
It seems to say online that collections are just any object that can contain a variable amount of elements though.
Yeah, like an array, list, dictionary, queue, etc . . .
Yep. That. You suddenly jumping in with the stackalloc and spans could make them think that it's something specific to that.😅
Why was that statement pointed to me then. :p
Oh maybe ambiguity.
By them you meant the guy.
I believe they're saying that jumping to using a Span and stackalloc is too advanced and will confuse them if they're trying to understand what collections are . . .
Ahah, I see . . .

But yes, Span is a cool thing to use . . .
Actually I just realised, if we're using arrays each time, and we're not mutating them, you can just make a static read-only field.
Make the type ImmutableArray<> too.
What is the equivalent of animation blending /transition time in code? Is it Lerp or MoveTowards? Im using code to animate and rotate an object but i would like to use its current pos as a starting factor then move toward the target quicker over time
how would i fix the weapon? i don't know why its being bugging!
Ultimately both transition between one value and another. Lerp does it based on the third parameter(between 0 and 1), which makes it closer to blending, while move towards moves it by some defined value.
With lerp you can control the time of the interpolation more easily, but it's possible with move towards as well with a bit of math.
thanks!
If using Lerp, download the Easings.cs script online to add easing to the animated value. A must-have for all projects . . .
Or just use a custom animation curve within Unity . . .
thanks!
{
return Mathf.Lerp(currentValue, targetValue, curve.Evaluate(timeElapsed / duration));
}```
Is this correct?
Yes, but you want to put the starting value, not the current value. Using the current value that is returned from the lerp will create an easing at the beginning . . .
ah right
To put it another way, it eases exponentially.
I think that's correct. :p
well, the curve will be inconsistent, appearing exponential but actually entirely dependent on the rate it's called
I think it's close enough.
It's how I move my camera.
I honestly don't know what's up with cinemachine.
📃 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.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FloatingPlatformMovement : MonoBehaviour {
float MovementScaleY;
float LoopDuration;
float Overshoot;
float IndicatedPosition;
// Use this for initialization
void Start () {
transform.scale.y = transform.scale.y * MovementScaleY;
bool IsGoingUp = TRUE;
float InitialY = transform.position.y;
float UpperBound = intialY + MovementScaleY;
float LowerBound = intialY - MovementScaleY;
}
// Update is called once per frame
void Update () {
if (IsGoingUp)
{
IndicatedPosition= transform.position.y + (MovementScaleY*Time.deltaTime * (1/LoopDuration));
}
else if (! IsGoingUp)
{
IndicatedPosition= transform.position.y - (MovementScaleY*Time.deltaTime * (1/LoopDuration));
}
if (LowerBound<=IndicatedPosition<=UpperBound)
{
transform.position.y = IndicatedPosition;
}
else if (IndicatedPosition>=UpperBound)
{
Overshoot= IndicatedPosition - UpperBound;
transform.position.Y= UpperBound - Overshoot;
}
else if (IndicatedPosition<=LowerBound)
{
Overshoot= LowerBound - IndicatedPosition;
transform.position.Y= LowerBound + Overshoot;
}
}
}
So does this look right?
What is the problem
Like I can edit the MovementScaleY and LoopDuration variables per instance right?
If you made them public or serialized you could
what's the difference?
[SerializeField] lets you set it in the inspector without making it public
@glass urchin To add to that, when you don't write public or private or anything, it defaults to private. So all your variables are inaccessible to other scripts or the inspector unless you serialize them or change them to public
Best to keep them private unless you NEED them to be public (which you rarely do)
Also a bunch of other errors I'm looking at.
a bunch of my variables "don't exist in the current context"
because they dont, you only declare them in the start method which make them local variables. they stop existing once the method ends
If you were getting errors you should have said so
What is IsGoingUp?
You have no variable by that name
<= is valid syntax, fix your errors one at a time
its a boolean. and i havent even added the code to make it change once it's going down
is your !ide configured? i just noticed the bool IsGoingUp = TRUE; (which is inside start as i pointed out above)
This wouldnt be valid code and your IDE should be screaming at you in red
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'm not using an IDE
well, start then
Big L
what about monodevelop?
MonoDevelop hasn't been a thing for like 5 years
just use visual studio, the guide on how to install/configure it is in the bot command above
my problem is that transform.position.y is only the component position. I want to change the position of the game object
Sounds like https://unity.huh.how/compiler-errors/cs1612
You'll need to have a properly configured ide to get help on this Discord server though
you have a lot more problems than that. worry about one problem at a time, your problem right now is the IDE.
After that, you can actually see what your errors are
I'm gonna see how much I can do without coding then.
I cant imagine you'll do anything, since you wont be able to build your game with errors
uhh . . . transform.position is the position of the GameObject . . .
You have many problems but this isn't one of them
a component does not have a position; it's an instance of a MonoBehaviour object which is attached to a GameObject . . .
is there a way to smoothen and slow down GetSpectrumData() ? basically i want to draw a wave that is very simple with very minimal up and down
Why isn't this working? I have it working when the "doorCollider" is set to collision but when I try to use the doorCollider it doesn't work. Also the doorCollider works but only without TryGetComponent?c# private void OnTriggerEnter2D(Collider2D collision) { if (doorCollider.gameObject.TryGetComponent<PlayerInput>(out PlayerInput s)) { print("HitEnter"); } }
Then it seems like doorCollider has no PlayerInput
Why is that happening?
Why is what happening
Are you saying that the doorCollider is not detecting the PlayerInput?
I am saying that doorCollider has no PlayerInput component on it
This code checks if the gameobject that the Collider collides with has the "PlayerInput" Component. Not that the object itself has it?
No, this code checks if doorCollider has the PlayerInput component
Whatever doorCollider is
doorCollider is a Collider2D
Okay, and does that GameObject also have a PlayerInput on it
Non have it. The player that collides into it does.
If doorCollider does not have a PlayerInput on it then that would be a good explanation as to why doorCollider doesn't have a PlayerInput component on it
Left is Player, Right is the Door Gameobject
Is this the object doorCollider is set to
Yes, the right one is.
And does that object have a PlayerInput component on it
Then the code is doing exactly what you told it to do. You're checking if doorCollider has a PlayerInput component, and logging if it does. Since doorCollider does not have a PlayerInput component on it, nothing logs
I understand xD
How can I make doorCollider like collision?
Why don't you just check the object you collided with for the PlayerInput component?
Example?
Exactly what you have but using the object you collided with instead of doorCollider
I don't know how to do that, can you show a Example?
How to do what? Your code is already doing it, just on the wrong object
I don't understand what you are saying?
collision is a reference to the collider you collided with
Your code is ignoring it
And instead checking doorCollider for the PlayerInput component
Just use the right object reference
So don't ask for PlayerInput? Just another Component?
No...
I didn't say that
Just call TryGetComponent on the right thing instead of the wrong thing
Can you just send me the code you are talking about? Here is the code I am using: ```c# private void OnTriggerEnter2D(Collider2D collision) {
if (doorCollider.gameObject.TryGetComponent<PlayerInput>(out PlayerInput s)) {
print("Door Collision");
}
if (collision.gameObject.TryGetComponent<PlayerInput>(out PlayerInput s1)) {
print("Collision");
}
}
Just take your code and replace doorCollider with the actual object you collided with
You're massively overthinking it
This? c# if (TryGetComponent<PlayerInput>(out PlayerInput s)) { print("Door Collision"); }
is this the same code you used in this screenshot? Because the debug that you see "Collision" should really tell you which object is the one that has the PlayerInput on it
Collision shown is just a String. It is the same code.
I know that it is a string, but since that is the only thing printing in your console, which of the if statements do you think is correct?
Are you referring to this? c# if (playerGameobject.TryGetComponent<PlayerInput>(out PlayerInput s)) { print("Door Collision"); }
the collison.gameObject, the doorCollider.gameObject isn't
I'm now just confused why "collision" is working and not "doorCollider" because they are both Collider2D ?
Because collision is the object you hit. doorCollider is not the object you hit
They're different objects
Is there a way to combine them? I just need collision to be the BoxCollider2D on the Object. I want to add a CircleCollider2D and collision won't let it function as I want.
what do you mean "combine them"
they're two different objects
You literally sent me two inspectors
these are different objects
collision and doorCollider are variables that refer to different objects
is there another way to refer to the incoming Object?
why do you need another way
you are really overthinking this
you've already found your answer in which object has the player input component
collision is the incoming object
You have the way to refer to the object you hit. It's collision. Why do you need to refer to it a different way
using collision will result in the code reacting to all the Colliders on the Object. I want it only to react to the BoxCollider2D.
You cannot
So the other option is to reference the GameObject with PlayerInput?
There is no way to collide only with a specific collider on an object
why? you should explain what purpose this has in your game. This is a XY problem
if your player has a collider thats not necessary, remove it
the door shouldnt be suffering because of an issue with the player
I have a Door. This Door has a BoxCollider2D and if the BoxCollider2D collides with the Player, it should change the scene. The Door will also have a CircleCollider2D which will start a door animation before the Player Collides with the BoxCollider2D.
Then these should be different objects
Seperate them into two different objects with two different tasks
Door
- DoorAnimationTrigger
- SpawnPointTrigger
So make a Child that changes the Scene, and the Parent will set off the Animation?
However you want to organize it, as long as the two colliders are separate and handling their own things
I litterally thought that "collision" effected even the Parent of an Object
Thanks for the Help!
How do I make a game object always have the same rotation so that when it collides with another object it doesn't just start spinnin?
Guys can I just get models and graphics like ue4/ue5 in unity?
Lock the rotation on the rigidbody
thanks
If you steal these models from ue4/5, sure😬
How?
That was a joke obviously. You're not limited to what assets you use in any of the engines.
Same as any other game. Time, effort, development experience. Probably a team with these 3 things and a budget.
Any engine
Then how they make a seperate website?
Host it on a server.
How
*host the WebGL build on a server.
I have repl website
Rent a server. Setup the environment, upload the build.
I have my free repl website
I'm not sure if it's enough for a WebGL build, but you are free to google that.
This is not really unity related question.
smash karts is a webgl unity game. it uses photon PUN 2 for multiplayer and firebase for user services.
if you want to host a webgl build for free, you can use Unity Play or itch.io.
Right now when I press play my spaceship immediately points toward the direction I click, which is what I want it to do but not on the x-axis (since I'm doing it in 3d my spaceship moves on the y and z axis and I can't figure out how to make it x and y). I'm trying to get it to like turn towards where I right click without rotating any other way. How do I do that?
You can use the animator, the legacy animation component or some custom implementation for animations.
Ok
Can u provide me yt video for it
Do you expect me to google for you?🤔
@nimble scaffold what is your goal? you're very early on this journey
that is pretty ambitious
like a single player first person shooter?
Aeon Valor is the name
Multi
But fusion isn't working
At all
You'd need to decide on the plane of rotation or an axis that you want to rotate around. If you want it to be orthogonal to the view, then it's(axis) probably equal to the direction from your ship to the camera.
for reference, this is the highest quality fps sample available for unity: https://github.com/Unity-Technologies/CharacterControllerSamples/blob/master/_Documentation/Samples/onlinefps.md
however you need a lot of sophistication to use it
is there an easy way to depict a 3 dimensional graph in 2d like this?
Like what? All this shows is some bounding box. What's the use case in your game
oh, to clarify, im making a game for my thesis that's essentially a practice tool for engineering students early on in their course. this is specifically for adding cartesian vectors so as part of the question i need to be able to depict a pair of 3d vectors. i need a way to show the 3d graph basically
What about the part about depicting it in 2d? I'm not sure what that part implies
I would just use line renderers to visualize the vectors easily
oh right, well i just meant im using unity2d. my problem is like, accurately showing the angles in "3d space"
ive tried messing with this arrow renderer i have and trying editing the rotation of the vectors as if it was on 3d
How to import it in unity?
Does this have to be 2d? You could definitely just set these all in 3d space and be done with it. They just directly take in the positions you want and that's all. I dont know how this would be in 2d which I assume you're using an orthographic camera for
I have implemented a pool system for my particles. The pool system has been implemented correctly but the particles do not play. They are play on awake and to play them, I disable and enable using setActive(). Also, delay some frames between disabling and enabling but it does not differ.
If I disable and enable them through the inspector, afterwards, they start playing!
ripplePSInstance.Clear();
ripplePSInstance.SetParticles(_ripples, rippleCount);
ripplePSInstance.gameObject.SetActive(false);
await UniTask.Yield();
await UniTask.Yield();
ripplePSInstance.gameObject.SetActive(true);
await UniTask.Yield();
ripplePSInstance.Play();
The combinations of it have been tested
it definitely doesnt, again ive tried editing it in 3d and stuff, ill mess with it some more, just looks a little wonky is all? maybe its skill issue
We can make a thread and if you want to show the code, I can have a look in a few minutes
It 100% should just be 3D and then rendered orthographically
thatd be really helpful, sure!
Anyone please help me witg this topic
That package is for an ECS character controller; I doubt it's what you want
Yeah I want it
pangloss giving lazy suggestions again 💀
Do you know what ECS is 
Idk
Then you probably won't find any use for that example
If you can't import it yourself, you probably wouldn't be able to build your game on it.
Start simpler
well, then you've got to learn an entire different paradigm of working with the editor and programming in Unity https://docs.unity3d.com/Packages/com.unity.entities@latest/index.html
You should not be doing this, and nobody is going to entertain this. Multiplayer as a first project is silly enough, let alone multiplayer ECS. It ain't happening.
Kk
whats does the curve do?
From the name, changes start size.
during it life time?
Hey all!
Is there a way to simply "do something once only when a variable's value is x" without having to use a bool?
so like if I have a variable, lets call it amountOfStuffInRange
and I want something to happen only once, any time amountOfStuffInRange's value goes to 0
and I know I can accomplish it with a simple bool check, but is there another way? thats maybe less cluttery?
check it only after it was modified
then just use it
Avoid modifying it after that event occurred.🤷♂️
no need to check it in update loop
But itd continuously keep checking it tho? I might be misunderstanding something a lot here haha its a bit early here
is it possible to align GameObjects on the position of an Arduino?
If you move the Arduino that the GameObjects move aswell?
Im using the HoloLens so the gameobjects are "holograms" that need to be set to the Arduino device. If yes, what Arduino compononent would fit best for this case?
use a method or property to change it, then you can do your other logic in there only when its changed rather than every single frame
There are 2 states you have: the state(value) of the checked variable, and wether it had the desired value once or not.
If you have 2 different states you can't possibly keep track of them without 2 variables.
Hold on let me see if that works
you might want to ask this more in an arduino related group, because the unity portion of this is not an issue. its as simple as setting the position. you need some communication between arduino position in real life and unity
ah okay ill do that instead
Okay now it works! Thanks a lot!
What is this? When does it appear? Give some context.?
not really sure i move my project file to my laptop and and it got this error
but its good now i moved the plastic4 from my pc to my laptop now its fixed
Hello, I used some Textmeshpro Text elements in my game, and it resulted in showing these giant blue text symbols while playing. Any idea what is up?
It's the gizmo for TextMeshPro texts. You can disable it in your gizmos menu if you want.
thanks. And I guess same to hide the canvas outlines?
Not sure to be honest if that's a gizmo, but you can look for it in the same menu
you can use eyeball icon in hierarchy
Hello, I'm wondering if there would be a better way to tackle my problem.
Basically I have an array, each element in the array has a partner and I need to specify a point between those 2 specific partners, the way I'm doing this seems inefficient, would it be better to use a dictionary for example?
This is the way each element is partnered, you can see the intervals are irregular so I used for loops with 2 iterators to achieve this
post it with formatting please !code this isnt readable
📃 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.
in window, you can use window icon key+print scene to screenshot
Hello, doesnt awake only run once and at the start of play mode?
_playerInputActions.Player.Interact.performed
Will this code run when the button has been pressed at any time of the game?
or should i keep it in update
It runs the first time the object is activated. If it's activated on scene start, it would be called then. Otherwise when it is activated.
Docs:
https://docs.unity3d.com/ScriptReference/MonoBehaviour.Awake.html
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
So the performed event work since its never being called as i am not pressing the button when awake is being called?
I don't know the context, so hard to say anything.
Maybe i should ask in input system. Thanks!
Make sure to provide some more context with your question and preferably some code too(not just one disconnected line)
Not entirely sure I understand the question. Are you asking about how to add elements at certain points in the array?
create a mapping so that you can get the partner by directly accessing the mapping
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i think this is my mapping
honestly its really hard to understand what the code is doing at a quick glance, you might want to cache some of these values for readability first. A dictionary or class could help you pair values together, so you dont need to calculate or lookup what the index of the other object is.
Whats the use case of this?
@eternal needle to create a "Mesh Cube" or frame at runtime that has specific points which dictate the shape of the frame/cube
sec ill grab screenshots
switch((index&0x4)==0x4){
case true:{
return index-4;
}
case false:{
return index+4;
}
}
```this is much easier to understand, or
```cs
return index-(((index&0x4)>>1)-1)<<2);
```branchless version (just for fun version), i wont suggest you use this even if you understand why it works
the idea is mapping 0 and 1 to -1 to 1 by 2*x-1
i dont really know what array you were talking about for the partner, but these definitely sound like you can throw both of them in a single class then do your calculations. I would really just map these by storing the objects together in the first place.
i dont really see why most of this is being done so its really hard to suggest anything. all of these numbers just seem like pure hardcode. the only other code i see is that you are getting the average between 2 positions (though sometimes you use localPosition).
also that screenshot really doesnt help anything here, its just random shapes mirrored
This was the code. Hope u got the gist.
https://gdl.space/aqejetotam.cs
@eternal needle this is the way I'm currently defining the colliders, which also seems inefficient to me
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
everything is currently stored as a prefeb, but I want to be able to add more points at runtime when a specific GameObject is clicked on, then the partners would change because the initial Frame isn't being interacted with anymore
idk if I'm even explaining this or if it's just confusing
how do you add a tooltip in visual studio when hovering a variable or enum value for example or a function ?
in VScode i would do this but it doesnt seam to work for me
// description var
public float something;
something += 1; //when hovering "something" it should show "description var"
!vscode
oh you mean regular 
i mean in unity i am having troubles
what
when i code in something else my example works
except if there is something special in VS 2019 with unity
yes you need to install unity workload
my code example doesnt show the text when mouse hovering
VS extension ?
follow this config
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
its a "Workload" part of VS Installer workloads
Yea sorry I dont really know what you were trying to explain. Based on what i understood, i still suggest grouping these points via a class or struct. Really just anything so you can avoid what you are doing with i,j,k in your first code
already done
huh?
evrything is fine except this tooltip thing
my VS is setup already since weeks
I think you just want to add a /// <summary> to it
if you just type ///, at least in visual studio, it should autogenerate the whole summary part. for methods it adds whatever params you have as well
ty that was what i was looking for
regular // works in VScode but i didnt know the equivalent in VS
Yep this should be called as long as the object is alive.
How? when awake has already been executed
Because you're subscribing to an event. As long as it's invoked, the subscribed method should execute
I confused subscribing with Invoking. 🤦♂️
public float qTimer = 0.0f;
public float qTime = 3.0f;
void Update()
{
if (inQueue.Count > 0){
if (qTimeCheck()){
Debug.Log("Agent: " + inQueue.Peek() + " has been in Queue for 3 seconds");
}
}
}
private bool qTimeCheck(){
qTimer += Time.deltaTime;
Debug.Log("time in Queue: " + qTimer + " Max Time: " + qTime);
if (qTimer > qTime){
qTimer = 0;
return true;
}
return false;
}
Does anyone have any idea how on EARTH qTime can be 0?
I've looked through the document with Ctrl + F for it and nowhere else do I mention qTime
Yet somehow when I print it, it's set at 0 even tho I initialize it as 3
wondering for a mechanic im implementing
is is possible to turn a sprite fully white using only scripts in unity 2d
what is the value of qTime in your inspector
Any ideas? bullet is not accurate on 60 degrees camera. It's all good when camera is 90 degrees. But my game is on 60 degrees
the projectile launches from rangedAttackPoint and the direction is changing based on mouse cursor
this is my RangedAttackScript:
using UnityEngine;
public class RangedAttackScript : MonoBehaviour {
private Rigidbody _rigidbody;
public int damageAmount = 0;
public GameObject rangedAttackPrefab;
public Transform rangedAttackPoint;
public float bulletVelocity = 30f;
public float bulletPrefabLifeTime = 3f;
public void InitializeRangedAttack() {
GameObject rangedAttack = Instantiate(
rangedAttackPrefab,
rangedAttackPoint.position,
Quaternion.identity
);
rangedAttack
.GetComponent<Rigidbody>()
.AddForce(rangedAttackPoint.forward.normalized * bulletVelocity, ForceMode.Impulse);
Destroy(rangedAttack.gameObject, bulletPrefabLifeTime);
}
}```
the codelet that handles player facing rotation:
```cs
private void HandleRotation() {
float rayHit;
Vector2 mousePosition = _inputActions.PlayerActions.MousePosition.ReadValue<Vector2>();
Plane playerPlane = new Plane(Vector3.up, transform.position);
Ray ray = Camera
.main
.ScreenPointToRay(mousePosition);
if(playerPlane.Raycast(ray, out rayHit)) {
Vector3 targetPoint = ray.GetPoint(rayHit);
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
transform.rotation = Quaternion.Slerp(
transform.rotation,
targetRotation,
100 * Time.deltaTime
);
}
}
Check the setting in the Inspector. That takes precedence over what is in code @delicate pewter
any code? any context? any expected behaviour? any ideas about what?
if you can't properly ask for help we can't help you
dont ask to ask: https://dontasktoask.com/
i am getting a VS warning when adding _ in a enum var, but not with other regular types
i am curious, why ?
is there a tech explanation
!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.
No, because it's (likely) a style issue. Show the code and the warning
private enum _Elements {
None,
eFloorBox
}
just in case : i dont have any problem when running the code
It's just a styling rule, you don't start enum definitions with an underscore, the same way that you don't start class or struct names with it either
Note that that's not a variable
ah okay, i just wanted to use a underscore because all my private vars starts with it
i always seen enums like a var type :/
variable types are also not variables
ik im just saying i foget that enums arent like other "classic" vars
That's not a variable declaration though. That is a type declaration like a class. There would be no problem with putting an underscore on the name of a variable. But again, this is not a variable
This might help you to understand better the naming conventions of unity: https://unity.com/how-to/naming-and-code-style-tips-c-scripting-unity
inQueue.Enqueue(new KeyValuePair<int, GameObject>(i, RVOAgents[i]));
I dont understand this error, how on earth is it saying that im flipping them
its clearly Int, GameObject in both
i is an int
RVOAgents[] is a list of GameObjects
show declaration of inQueue
regarding interfaces, where should i declare them ?
outside classes
okay ty
also, i never see anything like this, could someone explain what this means (i took a random example)
get {return m_maxHealth; }
set {m_maxHealth = value; }
these are properties
what are "properties" in Unity ?
that specifically are the custom getters and setters of the property
for some reason under my platforms i have these dotted lines
but i get stuck on them
how can i fix this?
i only get stuck on them for a second before falling through it
it's a C# thing, not specifically Unity. Look "C# Properties" @shrewd swift
Don't cross post, also this has nothing to do with coding.
oh okay, so instead of doing a regular variableName = value, you "use" whatever is in the {}
you can think of them as variables, but you can customise the behaviour of what happens when you get or set them
yeah, something like that. I recommend you read up or learn up on them
they're pretty useful
mb, im new to c#
no worries
you can do stuff like this for example
get {return m_maxHealth; }
set
{m_maxHealth = value;
UpdateHealthUI(value);
}
what does { get; } do ? a default set with no editing ?
yes. I believe that's called an auto property? It's been a while for me
shortcut ig
yes
its cool working with c# after being "forced" to use visual scripting
you got more possibilities and you truly understand the tech and technical limitations
in a custom script ? and add the script to every objects that will use the interface ?
im quite confused around this, should i create 1 script file per custom class ?
im legit on it xD
thats why i am asking those questions
I would usually declare classes in their own file, unless it's a plain C# class that's used as a data container that's to be used in a particular script
but no harm in just declaring classes in their own file
okay
so this path ?
or does the interface is "declared" everywhere by its own
doesnt that tutorial teach you how to implement interfaces
no
it does
the only mention is:
You can declare an interface as you would declare class or struct, but using the interface keyword.
You're confusing declaration with implementation
yeah you have to add your interfacename after "monobehaviour", but do you add the script containing the interface t oyour gameobject ?
yeah i think
you do not. because interfaces are not components
i'm thinking you'd benefit from a video
https://www.youtube.com/watch?v=MZOrGXk4XFI
📝 C# Basics to Advanced Playlist https://www.youtube.com/playlist?list=PLzDRvYVwl53t2GGC4rV_AmH7vSvSqjVmz
🌍 Get my Complete Courses! ✅ https://unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
🎮 Get my Steam Games https://unitycodemonkey.com/gamebundle
✅ Let's learn all about Interfaces in C# and how ...
so i declare the interface a a seperate file script, and implement by just adding the name with the class?
you dont seem to understand the text. having a demonstration might help
let me watch it and i'll come back if i still got question (hopefully not)
i do not what ? create a script ?
you do not drag it onto the object
okay so i dont add it as a script component, but i have to declare it somewhere
please just watch the video first
👍
it was a very interesting video ty
now i understand why my questions were weird
the only annoying thing i can see is that you have to implement all interfaces methods
an interface is a contract
you promise you can do X, Y, and Z
If you find that you're implementing methods that make no sense for your class, your interface needs to be broken up
as an extreme example
public interface IWhat {
public void Hit(float damage);
public string GetFavoriteColor();
}
This interface is bogus. It's describing two concepts that don't belong together.

it's not annoying. it's part of the reason you'd use an interface
if you dont want all, then you wouldn't use an interface
The entire point of the interface is that the compiler can guarantee that no matter what the object does or what type it is or what it's a subclass of, you can be 100% certain that it has these specific functions with these parameters and return types.
If you didn't need to put them all then an interface is pointless. How would the compiler know if your class implemented that specific function when it doesn't even know what class it is
Any idea why Related keeps getting reset to 0 items?
public class RelatedRuleTile : RuleTile
{
public List<TileBase> Related;
public override bool RuleMatch(int neighbor, TileBase tile)
{
switch (neighbor)
{
case TilingRule.Neighbor.This:
return tile != null && Related.Contains(tile);
case TilingRule.Neighbor.NotThis:
return tile == null || !Related.Contains(tile);
}
return true;
}```
Nothing in this code
Try encapsulating the Related field and set up a break point on the getter. 
lol

Do u have a custom editor for it?
If that's everything then I don't think the problem is that it's getting reset I think it's just always empty. You're likely calling that function on a different instance than one that I assume you've populated in the inspector
I add something in the list, I click outside the object
click again and it's bvack to 0
why is this necessary?
was thinking it's just unity not saving the asset
Is this something in game or in editor?
hmm ig Imma just duplicate the entire RuleTile class
it used to work when I was working that
I just separated it and this version dont work anymore
(realized i also have to make its own editor script as well
)
actually, it's the editor script messing it up
a 400 line editor script 😭
Skimmed this https://gdl.space/kifiruquqa.cs, cant find anything that resets a field of an inheriting class of RuleTile though
private IEnumerator SmoothChangeCoroutine(int amountOfXPAfterCalculation, int amountOfLevelUps)
{
float elapsedTime;
var sliderValue = _experienceSlider.value;
while (amountOfLevelUps > 0)
{
elapsedTime = 0f;
while (elapsedTime < SLIDER_MOVEMENT_DURATION)
{
_experienceSlider.value = Mathf.Lerp(sliderValue, _experienceSlider.maxValue,
elapsedTime / SLIDER_MOVEMENT_DURATION);
elapsedTime += Time.deltaTime;
yield return null;
}
amountOfLevelUps--;
_experienceSlider.value = 0f;
sliderValue = 0f;
}
_experienceSlider.maxValue = ExperienceService.Instance.RequiredXPForNextLevelUp;
elapsedTime = 0f;
while (elapsedTime < SLIDER_MOVEMENT_DURATION)
{
_experienceSlider.value = Mathf.Lerp(sliderValue, amountOfXPAfterCalculation,
elapsedTime / SLIDER_MOVEMENT_DURATION);
elapsedTime += Time.deltaTime;
yield return null;
}
// Sometimes, precision issues of 1-2
Assert.AreEqual((int)_experienceSlider.value, amountOfXPAfterCalculation);
}
I have an issue where I'm using sliders (set to whole numbers) that are using floats in Unity. My ExperienceService uses ints, resulting in precision issues. Is there a better a way to handle this, or should I just accept that there should be a 1-2 difference tolerance in the assertion?
Hey, I'm having trouble trying to build my game in unity. I keep getting an error saying "cannot build player while editor is importing assets or compiling scripts" I saw one solution was to eliminate any "Using UnityEditor" from my scripts, i did that but it didn't fix the issue. Anyone know what I can do to fix this?
Looks like a case of lerp not ever having a third value of 1f.
Is that some kind of clamp?
i'm currently changing my gun from semi auto to auto
only issue is this code doesnt work for whatever reason to add a delay between shots
{
ammoui.SetText(ammo.ToString());
if (Input.GetButton("Fire1"))
{
Shoot();
}
}
IEnumerator Shoot()
{
PlayerShoot();
yield return new WaitForSeconds(0.4f);
}
void PlayerShoot()
{
if (ammo > 0)
{
float spreadvalue = (Random.Range(-7.5f, 7.5f));
Quaternion bulletRotation = Quaternion.Euler(0f, 0f, transform.rotation.eulerAngles.z + spreadvalue);
GameObject playerbullet = Instantiate(playerbulletPrefab, firePoint.position, bulletRotation);
Rigidbody2D rb = playerbullet.GetComponent<Rigidbody2D>();
rb.AddForce(playerbullet.transform.right * bulletForce, ForceMode2D.Impulse);
audiosource.PlayOneShot(shootclip, 0.2f);
Destroy(playerbullet, 5f);
ammo = ammo - 1;
}
else if (ammo == 0)
{
audiosource.PlayOneShot(emptyclip, 0.4f);
}
}
}
public int Health { get { return Health; } internal set { Health = value; } }
Does this work or do I need to create a backing field manually?
ienumerator isnt cooperating
work
and you will get stackoverflow
in my case? So thats not the way to do this then? 😄
just like this:
public void SetA(int a){
SetA(a);
}
public int GetA(){
return GetA();
}
```property is shorthand of method, but they are still function call
Alright, thanks
coroutines are started using StartCoroutine(MyCoroutine())
First off, you aren't starting the coroutine. Second off, that coroutine is completely pointless, it calls the other function immediately, then waits 0.4 second and does nothing
hello!
does anyone know how can i check if transform.rotation.y is set to 90 degrees?
Bad idea. Don't rely on individual euler angles for things. Euler angles come as sets of 3 and individual euler angles don't mean anything on their own
a better option is to check if the object is facing "right" for example
which is probably what you really want to know
Something like:
if (Vector3.Angle(transform.forward, Vector3.right) < 10) {
// it's facing right
}```
10 being an arbitrary threshold value
this checks if you're within 10 degrees of facing purely to the right
.rotation is a Quaternion, a normalized 4D value. It'll never have any components at 90 because it's components have to add up to 1.
You could check if the .eulerAngles.y is a certain value, but considering that something being 90 on y is identical to being 270 on y and you have no idea how that is going to be calculated, you can't rely on it.
You should use the method Praetor is sending, or use Vector3.dot between your facing angle and the angle you want to check. If the dot product of those directions is near 1, it means they're facing the same way. 0 means they're perpendicular, and -1 means they're opposite
hi I need help
i was also thinking about using this
if (transform.rotation == Quaternion.Euler(new Vector3(0, 90, 0))) ;
would this work?
my camera zooms in to the feet of my character when i move it around
i am sure the x and z are always 0
it's just a bad idea because it requires perfect accuracy
better to go with a threshold
I wouldn't compare directly on the angle if it's moving beyond the 90
show the camera in the inspector
I started unity in today what do you mean by inscpetor lik the game mode?
click on maincamera then screenshot again
And what is the position of the Player object your camera is looking at?
hold on
Vector3(458.631012,27.1529999,154.957611)
very close to the one in the screen
try creating an empty gameobject as a child for the player gameobject and place it in the head of the player.
then change the "look at" in cinemachine to the new gameobject created
2 things to look at, i see 2 cinemachine camera named objects for player, is it switching to another one that is at the feet using priority. you could also have some suspect values in body or aim module
your player object's pivot is probably at its feet
the camera starts in the right position but when i move it sometimes it zoom in
how do i change that
you probably don't want to
you probably want to do this #💻┃code-beginner message
place it in the head of the player? like drag it on top of the player?
move it by the arrows so that it is "inside" the head
but make sure it is a child of the player
Because now you're looking at the player's head instead of their feet
The thing you tell it to look at will be the thing it looks at.
i think he meant why does it now zoom on the feet anymore
Because now it's looking at a different object
and that object is not at the player's feet
i am looking at a tutorial and it should not zoom in even before this
Because it is now not being told to look at its feet 🤷♂️
That's the same as what we said but inverted
what tutorial send the link
This is tutorial#08. In this course you will learn 3d game development step by step using unity game engine by developing Third Person Shooter TPS zombie apocalypse and zombie survival horror game.
Follow us on our Instagram: https://www.instagram.com/wits.gaming/
Complete Course YouTube Playlist: https://youtu.be/tSkKIqvDTEM?list=PLA-xaldQ72r...
this seems kinda complicated for a beginner
i think you should try to make a simpler game
idk tho
Have you done this yet?
!learn 👇
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
If not, do it first
thanks
Hey, I wanna create 2d Teleportation. Basic idea is: stand on top of tele entrance, animation plays and player teleports to the exit. Exit has no teleport function, just acts as a waypoint. These will be created by the player so I wanna be able to grab the entrance and exit as prefabs
- create gameobject that has the animation
- on player script make 1 serializefiled Transform and in unity assign the exit gameobject to it
- instantiate the animation gameobject
- hide the player
- waitforsecond(you choose)
- transform.position = transform(from 2).position
if (gameObject.name.Contains("Fast"))
does anyone know why this doesnt work?
i also tried with ToString()
use Debug.Log(gameObject.name)
This is very vague. What do you mean by "doesn't work"? What part doesn't work? What is the failure state? Error messages? What's the intended behavior?
prove it with logs
ok
how would i set this text function to display with two variables that are in tostring functions
Combine them outside SetText, and pass the combined string in
Checking like that is pretty bad practice and can cause problems as you are seeing now. One way where you are not relying on typing the correct string is adding a new empty class to your gameObject named 'FastUnit'.
Then you can use:
if (gameObject.TryGetComponent(out FastUnit)
{
//Some code in here
}```
how do you want them displayed? Just one after another?
ammoui.SetText($"{ammo}/{totalAmmo}");``` for example
im currently creating an ammo system and want to have a seperating character in the middle
so like 12/60
(ammo + totalammo).ToString();
pls use camelCase for variable names
That would add the values together
Not concatenate the strings
Right?
ye it wasn't obvious what he was trying to do.
yea it works, there was another problem
There always is. This is why we debug
ty for making me see that 🙂
the problem is never going to be "basic operations in C# don't work"
I'm trying to get my VS code to work again but It ain't and I don't know if this is the problem
Regen Project files and open Output tab on vsc
I click regen project but nothing happened and I have VSC open
you opened script form unity after that? screenshot the output tab
Wait, I think I got it working. Seems like the old tab kept opening back up instead sorry
oh cool at least its working lol
True
public class Grapple : MonoBehaviour
{
private RaycastHit lastRaycastHit;
[SerializeField] private float maxDistance = 2f;
private bool PullSurface = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 origin = Camera.main.transform.position;
Vector3 direction = Camera.main.transform.forward;
RaycastHit raycastHit = new RaycastHit();
if (Physics.Raycast(origin, direction, out raycastHit, maxDistance))
{
if (raycastHit.collider.gameObject.CompareTag("GrappleAble"))
{
print ("Can grapple to!");
transform.position = lastRaycastHit.point + lastRaycastHit.normal * 2;
}
}
}
Why does my character not teleport when it looks at a object?
is it character controller ?
My character does have a controller why?
if you're using the character controller then you disable it before teleporting, then enable it again
Ah, got it
How do I disable it?
Ah, thank you!
Now my character goes below the ground for some reason
you'd have to provide more info
So when my character teleports it just goes underneath the ground for some reason. Not the target I aimed at
whats the current code ?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Grapple : MonoBehaviour
{
private RaycastHit lastRaycastHit;
[SerializeField] private float maxDistance = 2f;
private bool PullSurface = false;
CharacterController characterController;
// Start is called before the first frame update
void Start()
{
characterController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
Vector3 origin = Camera.main.transform.position;
Vector3 direction = Camera.main.transform.forward;
RaycastHit raycastHit = new RaycastHit();
if (Physics.Raycast(origin, direction, out raycastHit, maxDistance))
{
if (raycastHit.collider.gameObject.CompareTag("GrappleAble"))
{
print ("Can grapple to!");
if (Input.GetMouseButtonDown(0))
{
GrapplePull();
}
}
}
}
public void GrapplePull()
{
characterController.enabled = false;
transform.position = lastRaycastHit.point + lastRaycastHit.normal * 2;
characterController.enabled = true;
}
}
I'm thinking of changing this line cs transform.position = lastRaycastHit.point + lastRaycastHit.normal * 2; for now to have it at the game object a certain amount above the object looked at
you don't appear to be assigning to lastRaycastHit anywhere
Wait
rip
I do, at the top\
the new one is out raycastHit
private RaycastHit lastRaycastHit;
I'd just pass the RaycastHit as a parameter to GrapplePull, it's easier
No need for a class variable
first of all, that's the declaration not an assignment. second, how do you expect it to be the last raycast that hit instead of its default value?
To be honest, when I see last raycast I though the last thing it has hit. So when it's called I thought the last thing should be the object that I looked at
how could it be the last thing you hit if you never assign to it?
Your code editor is probably graying out that lastRaycastHit field, telling you it's not used and can be removed
That's a hint you're not putting a value into it ever
It's used. It's not grayed out
Never assigned to then, it'll ask you to make it readonly
what would this print?
string myName;
string name = "Boxfriend";
Debug.Log(myName);
Nothing
exactly.
so now how is lastRaycastHit anything other than nothing (or rather it's default value which is basically the same thing)?
I'm taking the RaycastHit and calling it lastRaycastHit. Then using it down for the teleport
Nope
and i made a string called myName and printed it
you do know what it means to assign to something, right?
Yes! it's assign a vaule but i just seen that raycastHit is not being used for some reason
So the raycastHit is not assiging lastRaycastHit
why would it? on what line are you expecting lastRaycastHit to be assigned the value of your raycastHit local variable?
private RaycastHit lastRaycastHit;
That is a declaration, not assignment
That is a null variable
Why would that line assign the value of your raycastHit to it
there are beginner c# courses pinned in this channel. please start there.
default value, not null. it's a struct 😉
Ah, yep. Mb
Misunderstanding between local variables and fields. Your Physics.Raycast assigns to the local variable, declared 3 lines above
The local does not exist outside of Update
ugh.. did ms just made vsc valid for unity again? anyone seen this before?
How should I fix that?
Thanks for that help...
Assign to the field, not the local variable (you don't need the local, technically)
Ah, alright
Thank you
this extension was updated by microsoft months ago
vs is still better though
this animation does not seem to exit, I have a trigger that fires once you enter the box trigger, then it continuously loops the prayer animation.Does someone know what I am doing wrong?
do triggers fire once or do they continuosly fire?
Triggers are one-time use. Once read, they reset
When I switch the field with the local but now it's saying that I need to set a object on line 29 even though it's meant to look for a tag
this code only fires once when I click "F" and yet the animation keeps going back to the prayer anim
Why are you setting the trigger twice
I was trying to get it to turn off
its nothing, I just want it to go back to default state and stay
So, it's set to transition at the end of the animation
correct
which appears to be about 20 seconds long? Unless that timeline is in frames
yes I animated the prayer to be long and cinematic
And if during that animation you spend any frames with the F key pressed, it'll queue another one
Chances are when you hit the button, you've held it for at least one extra frame
so it's going to be praying for 40 seconds
ok, can I just use "getkeydown"?
Probably would be better
and only set the trigger once
#1180170818983051344 for work in progress stuff
alr then
how would i destroy all instances of an enemy with a specific tag if theyre inside a collision box
what part of that are you struggling to figure out?
Is it the destroying, the detecting, or the tag-checking
if theyre inside the collision box or not
Best way would be an overlap method. Then you can loop through the results and check their tags to destroy them:
https://docs.unity3d.com/ScriptReference/Physics.OverlapBox.html
so detecting them. there's a few options for that, you can rely on physics messages like OnCollisionEnter/OnTriggerEnter or you can use physics queries like OverlapBox
all these enemies have the enemydead tag, and what i want to code is that only the enemies inside the collision box get removed
while all the enemies outside stay where they are
this is unity3d tho
my game is in 2d
Then use the 2d one
ok im thinking
i create a new tag called "enemydeletable" and inside the radius all dead enemies get assigned that
only thing is i have to reassign enemies with the enemydead tag when the enemy leaves the radius
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class PlayerMove : MonoBehaviour
{
[SerializeField] GameObject camera;
private Rigidbody rb;
private float speed;
private float xAxis;
private float zAxis;
void Start()
{
speed = 5.0f;
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
camera.transform.position = new Vector3(camera.transform.position.x, camera.transform.position.y, transform.position.z - 6);
xAxis = Input.GetAxis("Horizontal");
zAxis = Input.GetAxis("Vertical");
Vector3 movementDirection = new Vector3(xAxis, 0, zAxis);
transform.Translate(movementDirection * speed * Time.deltaTime, Space.Self);
Quaternion rotationQuat = transform.rotation.normalized;
print(rotationQuat);
if (rotationQuat.x > 0.37)
{
transform.rotation = Quaternion.Euler(0.37f, 0, transform.rotation.normalized.z);
print("stop1");
}
else if(rotationQuat.x < -0.37)
{
transform.rotation = Quaternion.Euler(-0.37f, 0, transform.rotation.normalized.z);
print("stop2");
}
if (rotationQuat.z > 0.37)
{
transform.rotation = Quaternion.Euler(transform.rotation.normalized.x, 0, 0.37f);
print("stop3");
}
else if (rotationQuat.z < -0.37)
{
transform.rotation = Quaternion.Euler(transform.rotation.normalized.x, 0, -0.37f);
print("stop4");
}
}
}
I want to stop the cube from falling over when it approaches a slope, but the cube is rotating weirldy and stuff here is a video:
The weird thing is, that it keeps rotating the y axis. However I freezed the y rotation in the rigidbody
that's not rotating around the Y axis. looks more like either X or Z oh my bad, thought you meant the rolling
of course it is look into the inspector at the end
That's probably not because of the rigidbody, but by you setting the rotation directly
yeah could be but i set it to 0
Also, why are you checking individual values of a quaternion? Those values are going to be basically nonsense to any human
What are you trying to achieve by checking if the x component of a quaternion is greater than 0.37?
xD it didnt work with eulerangles
that the cube doesnt fall over 0.37 is abpout 45 degree
why do people insist on showing 20 seconds of unrelated stuff for the issue to only be the last 2 or 3 seconds of a video
0.37 as one component of a quaternion has absolutely nothing to do with degrees of anything
the first seconds are showing the buggy resetting
oups
ok i will look into that
A quaternion is a four-dimensional normalized expression of an orientation and is basically incomprehensible to people. The X, Y, Z, and W values have nothing to do with the X, Y, and Z axes of euclidian space
From my barest understanding, w is the amount of twist along the colinear composite of axes of xyz in a quaternion. It doesn't really work well when trying to use it directly
It's best to just consider them "Wizard math" and do everything in your power to never operate on them directly
how can I get transform.rotation.x to the numbers that are shown in the inspector?
you don't because transform.rotation is a quaternion
even transform.eulerAngles which are in degrees may not be the same as what you see in the inspector because they are interpreted from the quaternion at the time you access them
Does anyone know how to access this page? "Netcode -> general ->"
but there has to be a way
- this is not a code question
- #archived-networking for Netcode for GameObjects related questions (or even the netcode discord server)
- it's in project settings
Why even try? Why do you require them to match? Just work with your own numbers internally
But I have never seen a satisfactory way to make it match the inspector
with which numbers? eulerangles?
Numbers you declare and track, then use to plug in AS eulers
Like:
float xRotation
Vector3 cubeRotation = new Vector3(transform.localEulerAngles.x, transform.localEulerAngles.y, transform.rotation.z);
print(cubeRotation);
if (cubeRotation.x > 45)
{
transform.localEulerAngles = new Vector3(45, 0, transform.rotation.z);
print("stop1");
}
else if(cubeRotation.x < -45)
{
transform.localEulerAngles = new Vector3(-45, 0, transform.rotation.z);
print("stop2");
}
if (cubeRotation.z > 45)
{
transform.localEulerAngles = new Vector3(transform.rotation.x, 0, 45);
print("stop3");
}
else if (cubeRotation.z < -45)
{
transform.localEulerAngles = new Vector3(transform.rotation.x, 0, -45);
print("stop4");
}
like this?
Not to make transform.rotation match. The inspector shows a value for transform.localEulerAngles. There are an infinite number of euler angles that express the same orientation so it might not match the numbers but as a whole will match to orientation
i dont understand why this code is red, i pulled it off the unity documentation
nvm i forgot to assign values
Don't use =
because for some reason you've just copied the method's signature instead of actually calling the method
That is the default in the declaration
Oh yeah, there is more wrong than just that...
no
i have this piece of code which uses 1d axis values
public void OnMove(InputValue value)
{
Debug.Log(value);
}
how can i log the actual value of "value"
like that
I have 2 elements (player and enemy) in the same position when the game is running (enemy is with isTrigger true), but the transform value of X and Y is so much different for close positions.
Anyone knows what possibilities to this happens?
What is the best tutorials I should learn from???
your skeleton sprite is likely offset from the actual parent object
!learn 👇
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
hi everyone i dont uderstand why my coroutine dont work that dont wait 5 second this is my code (first time i use coroutine) :
using System.Collections.Generic;
using UnityEngine;
public class timer : MonoBehaviour
{
public int temp = 30;
// Start is called before the first frame update
void Start()
{
while(temp > -1)
{
StartCoroutine(Timer());
temp--;
}
}
// Update is called once per frame
IEnumerator Timer()
{
print(temp);
yield return new WaitForSeconds(5);
}
}
#💻┃code-beginner message
you need to actually Get the value of your action from the InputValue struct
and what happened?
it shows an error
Where?
U are calling yield after, not before
cannot convert from 'method group' to 'object'
coroutines do not delay the code from the method that started them. they can only delay what is inside the coroutine
sounds like you're forgetting to type something 😉
make sure that your !IDE is configured so you don't make silly syntax errors like that