#💻┃code-beginner
1 messages · Page 53 of 1
Then how did you expect your player to move?
i assume the script would have controlled a trigger to the input system
is there a seperate script needed for move composite?
i cant seem to find one in here
I mean yes you read the input from the InputSystem, but you dont do anything with it
my input reader i added to the player
it has a character controller / animator and input reader which has the move composite code in it
I solved it, what I was looking for was Sort Group for whoever needs it, you can put the children on any layer, and they will all act as if they were on layer 2. And sorry for not using the correct channel xd 🐱
You somehow need to get the MoveComposite to the PlayerController, you do that nowhere currently
with GetComponent<>() does it only look for the current object and is there a way to search the entire scene
GetComponent gets the component from whatever object you call it on
how do i create a move composite?
ok how do I do that?
Also should my game manager script be a singleton and do i have to make it hardcoded or should i just trust myself
That's not really something I could answer
You can use GameObject.Find() then find the object then do a component search
it's fine for singleton stuff
and loading the scene
outside of that yeah, you wouldnt use it
If it's a singleton, you shouldn't need to use any sort of finding. Even then, you should be using find of type, not find by name
public CharacterController CharController;
[...]
CharController.SimpleMove(MoveComposite);
Doing find by GO would be quicker I think, no? It cuts down searching through each GO
Find already searches all objects. You're just adding a GetComponent on top of that
I don't do it, but I assume that's the reason you'd use find at all.
FindObjectsOfType takes just as long as Find
Im coding my GaneManager RN and wondering if and how i should make it a singleton or if ive already done it right
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public NightManager nightManager;
public float powerDrainModifier;
public GameManager Instance;
// Start is called before the first frame update
private void Awake()
{
Cursor.visible = true;
}
public GameManager() {
Instance = this;
}
private void Start() {
powerDrainModifier = nightManager.BasePowerDrainModifier;// + addedPowerDrain ;
}
private void FixedUpdate() {
nightManager.Power -= Time.fixedDeltaTime * powerDrainModifier;
}
void OnEnable() {
nightManager.HourChange += OnHourChange;
nightManager.PowerChange += OnPowerChange;
}
void OnDisable() {
nightManager.HourChange -= OnHourChange;
nightManager.PowerChange -= OnPowerChange;
}
void OnHourChange(int currentHour) {
Debug.Log("time changed! It's now " + currentHour);
}
void OnPowerChange(float Power) {
Debug.Log("Current Power: " + Power);
}
}
Dont use monobehaviour constructors
use Start/Awake
so put the instance = this in start/ Awake
reopen the script?
yes, and check if the Instance already exists maybe
and add that code to it?
Its just code snippets that you need to put into your script, not replace it
if (Instance == null) {
Instance = this;
}
Currently, Instance doesn't really do anything. It's an instance variable that refers to itself, meaning that you can use itself to reference itself, which isn't really useful
is it this or am i checking not null my brain is sleeping rn
Instance ??= this;
Shouldn't use null coalescence with GameObjects or MonoBehaviours, they can be "null" without being null. == null covers this condition, but ? does not
Oh my bad, forgot about that
For example, if it's destroyed but hasn't been cleaned up yet
but now woldnt i just call GameManager.Instance whereever i need it?
Right now Instance is an instance variable. Meaning you'd need to call .Instance on an instance of GameManager
For that it needs to be static
As I said its just code snippets that you need to fit into your Code
You weren't supposed to copy paste that
That was supposed to be an example
you were supposed to read it and apply it to your own code
i typed it in myself
It's still copied whether or not you did it manually.
It doesn't magically work just because you put in the keystrokes
so was my way correct?
i sighted it and typed it myself
It's still copied whether or not you did it manually.
It doesn't magically work just because you put in the keystrokes
lol
oh my god he showed help so I did it myself but probably not right
its incorrect man
see the red lines?
I'm still not seeing how this is faster though. If you do a component search, you're doing a linear search through all the components per GO. If you're searching by type, are you not doing a full linear component search on each GO on the scene? The return is that of an array too, so it doesn't seem to stop at the first component found.
i need it solved
i wouldnt get passive agressive with someone whoes trying to help
considering they could just leave you to suffer on your own
not really that hard.
you can tell by the way people type
its subliminal
don't mind it so much
see where it leads to is a conflict of speech in the computer alike to caps lock conversations
Both use reflection to search each object. FindObjectsOfType doesn't go through each game object and call GetComponent on it, it goes through all UnityEngine.Objects and uses instanceof, which is exactly as fast as accessing a string property
keep at ease, be calm, nice, on the computer, and you will succeed
take your own advice
i am 🙂
although it is very obvious what the problem in your code is
You typed parts that were not supposed to be typed
yes, i can try to do it again
[...] was just to show the rest of your code not for you to type as well
Show code
The [...] was not the only issue
Again, you were supposed to see the example and apply it to your own code. Not plop it directly into your code just wherever
Lots of basic syntax errors. A space between Char and Controller.
It's outside the class
A few other things
I recommend a basic c# course
https://www.w3schools.com/cs/index.php
im in one but im doing this on the side at the moment
i think I can progress
tests and stuff
or i may just have to wait until my class is finished
focus on the basics first dont make the same mistake as many other beginners and be over confident
i understand I can be more confident with this
But i would more focus on learning to read basic errors that litterally spell out for you what is wrong
this website is what i used to get this far
Take a general course. Not specific narrow tutorials like that
It's an incredibly suboptimal way to learn
where at?
I linked a really good one to you
Or learn.unity.com and use the pathways
Why would you want to
ttyl good bye
What are you trying to accomplish with that
I'm making a 3D animation application.
So, what's the use case for cloning a scene
But why do you need to clone a scene specifically
I just don't know how I can make code to create animation projects.
I have no idea how any of this relates back to needing to clone a scene
I'm completely lost as to what you're even asking about any more
Then I would say do the other course I said. That is for C# with no Unity
Hello, I am trying to fix this error that is showing up on my console
It says it has something to do with the 'SaveManager
I have looked up the location in the code but don't know what to do here
It says it's located around line 343
Show SaveManager
Also, is your IDE configured? Looks like no
It's listed in the 343 line of WeaponController
No. Show SaveManager itself. Not where you try to use it
Only thing I am seeing in the search are SaveSystem scenes
Is this a script or component you are referring to?
Why do you not know what scripts there are in your project?🤔
Okay, so you didn't write that code?
no
You are trying to use the Type SaveManager, which would be script (and a component, because MonoBehaviour scripts inherit from Component)
Then perhaps that asset has a dependency that you didn't install.
Before anything else, I would fix your IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
From a quick look at the package contents, the SaveManager is included with it, so you either didn't import it, deleted it or renamed it.
in terms of conventions which order is preferred?
public static new
or
public new static
you don't new a static
in my case I needed to
That would shadow out a field from a base class I guess.
Rarely would you need something like that for static variables. The convention is what you choose it to be.
Show your case
public new static AssetManager Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<AssetManager>();
if (_instance == null)
{
_instance = (Instantiate(Resources.Load("AssetManager")) as GameObject).GetComponent<AssetManager>();
}
}
return _instance;
}
}
Inheriting from generic singleton, but property needs to be slightly different
https://img.sidia.net/ZEyI5/jEVaFoFE86.mp4/raw
I have around 200 NavMeshAgents here, is there any way to make them "respect" each other more and get stuck instead of clipping into each other?
Currently using this:
private void UpdateDestination()
{
if (!_hasTarget) return;
var newPos = _followTarget;
var currentPos = _lastPosition;
// if (Mathf.Abs(newPos.x - currentPos.x) <= 1f && Mathf.Abs(newPos.z - currentPos.z) <= 1f) return;
NavAgent.SetDestination(newPos);
_lastPosition = newPos;
}
Follow target is set every frame to the position of my player
Hello, I seem to be bouncing off what I feel ought to be a simple problem, and am hoping someone here might see something I don't.
Short version: I want to detect whether a 2D character is standing inside a "shadowed" area. I put shadowed areas on their own unique layer called "Shadows". Then, an ability script component on the character uses IsTouchingLayers to test against that layer like so:
ShadowLayer = LayerMask.NameToLayer("Shadows");
InHidingArea = this.gameObject.GetComponent<BoxCollider2D>().IsTouchingLayers(ShadowLayer);
Unfortunately, this always returns as FALSE whether I'm in, out, or touching the edge, of a shadowed area. Any ideas of simple things I may be missing?
Do the shadows have colliders
Yup! They have BoxCollider2D and Rigidbody 2D components. The colliders are marked as triggers; don't know whether that matters.
I'm not too sure but the method doesn't say anything about that.
Im connecting some script for a player controller model, does anyone know how to solve this?
Yeah I didn't see anything in the documentation; it defaulted that way and I hadn't switched it off.
Im connecting some script for a player controller model, does anyone know how to solve this
Could try just boxcasting around the player and see if that returns any different results.
Does the Character have to be on the same layer as the Shadow objects? I had been assuming not given that IsTouchingLayers accepts a layermask of multiple layers, which made it seem perfect for checking overlap.
Okiedoke, I'll have a look at that. Thanks for the suggestion!
Like you were told before, doing a basic c# course will solve this
I need the support from this channel, don't direct me to one, I have one already.
This is less of a unity problem and more of a general c# problem honestly
What is maxDistance and why are there random curly braces in the middle of your code
Google or even clicking the error code will give you your answer instantly
Check this script from Unity, it has a portion shown, it does not function.
In this tutorial, we’ll dive deeper into Unity Cameras with scripts that control their behavior. We’ll start out with a 2D Camera that works from any perspective (in this case, we’ll be using it in an overhead view). Next, we’ll move on to 3D with a Camera that smoothly transitions — with a flick of the mouse scroll wheel — from first-person to ...
well thats because you copied code again without even trying to understand what it does
I understand what its suppose to do, but the code is not functioning.
Maybe I am at error?
or he is the code creator
Figure out the code error then revise what you've typed
Probably because that's sample code not meant to be copy pasted willy nilly. Did you follow what the tutorial said it was for or just skip to the code block and start copying?
No I did do it myself, and then tried copy and paste after, and both failed to work.
So, I'll ask again:
#💻┃code-beginner message
Seems like you typed it and that's good practice, but if you figure out the error code, you'll notice your mistake
this part
"(currentDistance + maxDistance * 0.5f), updateSpeed * Time.deltaTime);"
"maxDistance" doesn't apply to it
Ignore that, what is the error code. What does it mean -_-
What is maxDistance
it means the max distance to travel in the game play of the camera controller player
like a measured street cross walk
No. In code, what is maxDistance
What type and where is it defined
The low res picture doesn't help but I see the error
so revise the code and connect the error to it
Look at the name of the second variable in your code, and compare that name to the variable you tried to use
Also, count your curly braces. Every opening one requires a closing one
Is this the channel for questions? I read the “read-me” channel and it was under the heading “scripting”
It is A channel for questions. If they are about code
Almost all the channels are for questions
oh okay, I searched for a few minutes for a proper channel for my question and it’s not associated with coding but with unity itself
thank you
anyone know why this text pops up after importing from blender to unity? animations wont play either, it's just a simple raise shield animation
Looks like the armature was not imported properly.
Not really a code question btw.
Forgive me if this is obvious, but a bit of searching the manuals hasn't helped so far:
If a method takes a Physics2D.LayerMask as a parameter, are the layers defined by this layermask the same as the GameObject layers that one sets in the upper-right corner of the inspector?
Or is it a different set of layers, in the same fashion that Sorting Layers are different from GameObject layers?
Layers in the top right are for the most part used for physic based operations like raycast and collisional checking. Sorting layers for 2D spriterenders is specifically for rendering ordering of sprites which is technically z-depth sorting.
The layer mask is a bit mask representing all the layers. Each bit corresponds to a layer index
And yes, it's the layers that you can assign at the top right of the GameObject
how would I go about acessing asset files from a script that I can run outside of runtime. I have a bunch of combat animations that I need to make override controllers / SO's for and would like to speed it up by writing a script. I just dont know how to do it in unity
Groovy, yes I knew it was a bitmask... I just wanted to make sure I wasn't trying to pass in stuff from a completely different category- I made that mistake the first time I was trying to find out how sorting worked, heh.
Thank you both!
Either AssetDatabase or Resources API I guess.
I like to make a LayerMask variable and set it in the inspector. Makes it a bit more clear exactly which layers I'm selecting, and no strings or bitshifting to deal with
Say, that could be convenient yes... thus far I'd been grabbing them individually with LayerFromString, knowing it felt a tad clunky.
You can also do some bit shifting if you're interested.😏
Only recommended if you don't neurotically change layers all the time like a chump (named aethenosity...)
It's actually the one time I prefer string operations because of that
I often use bit shifting to define the default value for the mask in the inspector.
Bit masks are really cool actually. They're like mini bool arrays that are not restricted anywhere(like jobs or ECS)
I use bit enums everywhere and unity surprisingly has editor support for them
about the player controller
Do you have autocomplete and error highlighting in your IDE?
Because I can't see where the error is supposed to be—have you saved?
I do have error highlighting
Idk why it don't shoe
When I double click on the error in unity
What lines are 787 and 873. You cropped the line numbers
and show the full stack trace
It's brings me to the line where I instantiate created arrow
I need some help. I have a game that i finished and i built in WebGL and everything was fine in unity but when i uploaded it on itch.io most of my UI elements and assets were out of place, not at all where they should be. I have set all my canvases to "Scale with screen size" etc, someone who has had the same issue and knows and tips and tricks?
To start with I would say your Reference Resolution is wrong, it should really be 1080HD.
Also you will need to go through everyone of your UI elements and check that you have set the anchoring correctly
I see, 1920x1080 and set all anchoring?
yes
should i put Match to 0.5? or is 1 correct?
0.5 is better, so the most accurate width or height can be used
thanks for response, i will try it!
You can also change your game resolution in your Game view in the top bar to see how it will affect things as far as I know.
even better you can run the WebGL build locally and then play with the browser window size
with firefox?
yes
ill try that to
i had trouble with compressed something something but i check "Decompression fallback" in publish settings, if that is the right way
because before i did that i couldnt even play it on the browser
Hey Im making a first person shooter and once i get finished killing all the enemies, i get thrown an error immediately.
PlayerController: https://paste.ofcode.org/UN9G2Rtaszq9gZLqCENVxR
GameManager: https://paste.ofcode.org/zgmW5fQMzrm8gBX8aRnuss
I am using the new input system, where i have an action set up for mouse clicks. in my inventory panel i want to figure out if the character preview (which is a raw image that shows a rendering texture) was clicked. how can I check that?
Hey guys, in a scriptableobject script. I create a cs Public Sprite sprite; Variable, but in inspector there is no option to select the basic ones like, circle, box etc. How do I do it?
You can do that with the EventSystem (part of UI, not InputSystem) https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.EventSystems.IPointerClickHandler.html
They should be in the assets tab.
OH,
its a big might idk if it is
np
thank you very much! although that system seems to be heavily focused on a mouse. how would i go extending it to a controller or other forms of input?
i have an problem. I have a game with different levels but when i play level 2, die and click on retry the game sends me back to level 1
Can you show your scene loading script when you die?
public void Retry()
{
SceneManager.LoadScene("Level " + StateNameController.CurrentLevel);
}
public void Retry() { SceneManager.LoadScene("Level " + StateNameController.CurrentLevel); }
public static int CurrentLevel; here's from the StateNameController Script
public void OnButtonPlayGame() { SceneManager.LoadScene("Level " + LevelSelected); CurrentLevel = LevelSelected; } and this is when i choose the level
!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.
Okay either of these should do what you want.....
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
Instead of giving it a ' hardcoded' value, just get what scene is currently open and load that.
Okay, I think, in your Retry method, before loading the scene you need to 'store' the current scene somewhere. (is your statename controller script accessible across all of your scenes?
how do i know?
Umm. If you wrote it, you should. 😕
oh
how do i make this scipt accessible across all of my scenes?
Hey! That errors are very common errors. You can check this link for solution
https://forum.unity.com/threads/nullreferenceexception-object-reference-not-set-to-an-instance-of-an-object.1511555/
Thank you!
Everytime, you don't know how to solve an error just go to forums and make a topic or see other topics from people handling the same error. Of course, you can ask whatever you want here to find solution to your issues 🙂
Pretty sure you know by now how this server works. Just ask your question.
I have an issue with Unity, my player will not move forwards when I press W, it will go in random directions
Sometimes it will, sometimes it will not
And ... are you going to show how you did it?
Now imagine someone else had asked this question, how would you go about answering it?
A blue square. Not a coding question.
Hey guys, I have a ScriptableObject. and I have 3 enemies. When I change the color of the enemy or the scale it works. But what about the sprite? I want one enemy to spawn with a isometric diamond shape and the other with a circle. But I am not being able to figure it out on start method, what should I write. Here is example of how I am doing with the color and scale.
void Start()
{
rb = GetComponent<Rigidbody2D>();
_player = FindObjectOfType<Player>();
// change the color of the experience to the SO Color
_spriteRenderer = GetComponent<SpriteRenderer>();
_spriteRenderer.color = data.color;
// change the scale of the experience to the SO Scale
_scale = transform;
_scale.localScale = data.scale;
// change the sprite of the experience to the SO sprite
_sprite = GetComponent<Sprite>();
}
``` But for the sprite I am not sure how to do it.
_spriteRender.sprite = data.sprite;
I did like that cs // change the sprite of the experience to the SO sprite _spriteRenderer = GetComponent<SpriteRenderer>(); _spriteRenderer.sprite = data.sprite;
but it is not working
Now its working thank you
ok i found a better way to explain my question
Trying to look at what
yield return new WaitForFixedUpdate();
``` Does and i cant find any good explainatons does it just do the stuff in the while loop on fixed update
t = Mathf.Lerp(t, 1, t);
t = Mathf.Lerp(t, 1, t);
t = Mathf.Lerp(t, 1, t);```
basically i can make a polynomial of any order by adding more mathf.lerp, but i wanted to know if unity has built in polynomial functions
linear, quadratic, cubic, quartic, quintic
What are you trying to do? Raise t to some power?
i just want to make polynomial curves basically
like a bezier curve is a cubic polynomial iirc
it tells the code to wait for a specific time, in this case 0.02 sec
which you can do with adding more lerps, but i wonder if there's a nicer way, like a polynomial function
So am i doing this right if i want to decrease the power by the base power drain + any added drain
public IEnumerator RunGame() {
Power = 100;
while (Power < TotalPower) {
HasPower = true;
yield return new WaitForFixedUpdate();
Power = Power - (BasePowerDrainModifier + AddedPowerDrainModifier);
PowerChange(Power);
}
nvm this is not working as intended
I dont think there is one builtin, I remember making these helper functions too
Inspired by this vid https://m.youtube.com/watch?v=mr5xkf6zSzk
it probably drains way too fast, you might want to change
yield return new WaitForFixedUpdate();
to:
yield return new WaitForSeconds(0.1f);
and then multiply the drain value by * 0.1f;
That way the drain will update 10 times per second and if BasePowerDrainModifier + AddedPowerDrainModifier is for example 25 then it would drain 25 energy every second.
use Debug.Log("Some Text"); to figure out which of the if statements is getting called.
You can also use Vector3.right instead of .left * -1
Like this?
public IEnumerator RunGame() {
Power = TotalPower;
while (Power < TotalPower) {
HasPower = true;
yield return new WaitForSeconds(0.1f);
Power = Power - (BasePowerDrainModifier + AddedPowerDrainModifier) * 0.1f;
PowerChange(Power);
}
}
ye should work
That while loop will never run
Power = TotalPower right before checking if Power< TotalPower
The FixedUpdate way would have been more consistent BTW.
should it be > instead
well i mean at the start of course the power would be the total power
oh shit doesnt it need to be <=
you probably want while (Power > 0)
also dont kill me for having capital letters for variable names plz
so also my way of doign FixedUpdate would have been better?
It shouldn't be WaitFor anything. Just yield return null and multiply the change by deltaTime
public IEnumerator RunGame() {
Power = TotalPower;
while (Power > 0) {
HasPower = true;
yield return null;
Power = Power - (BasePowerDrainModifier + AddedPowerDrainModifier) * Time.deltaTime;
PowerChange(Power);
}
}
almost thought something like this would work
depends on what you're expecting it to do
haha = StartCoroutine(uuu())
haha would be a Coroutine, not an IEnumerator here though
What do you need the reference for?
If you want to run coroutines in the editor you need to use the EditorCoroutines package
the goal of it is for like adding extra logic in case something is triggered, much like events
What does the IEnumerator have to do with "extra logic"? Are you trying to start a coroutine?
@queen adder Alternatively, you can use the EditorApplication.update callback. (It wouldnt be a coroutine, but you would be able to do the same thing)
https://docs.unity3d.com/ScriptReference/EditorApplication-update.html
Is there away get my coding coloring in vc because it all flat same colour. Never use virtuele code community
!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
Thx
Hi guys ! i'm using two unity app linked by tcp-udp connection, and i need to reload both current scenes, i was wondering if, by doing the basic reload, the udp-tcp connection cut instantly or if i have something else to do
scenes have nothing to do with IP connections
yeah so but reloading it nothing will change in terms of connections right ?
does anyone know how you get f.e. the rotation inputs in your script?
What do you mean by rotation inputs?
hello
need to create a mesh from point 1 to point 2
i already did the line renderer solution, need another solution with creating a mesh, anyone got an example of this?
well In the transform object you have the 3 rotations input on one line. Im assuming its also in one object so you can get the values like Object.x, Object.y, Object.Z Im not sure what I need to put to get the same results. Normally inputs are put under each other.
gameObject.transform.rotation = Quaternion.Euler(rotationX, rotationY, rotationZ)```
I want to put multiple coordinates on my object so I can access them later
I want to pre define the coordinates
ah yea, Quaternion is what I looked for
thanks
How do I allow a timeline to contain multi-scene references?
https://srcb.in/M8C4Ns0VrE yooo i need a little help everything woks fine but the jump.
use Debug.Log and make sure the code you expect to run is running when you expect it to run
sorry im very new where would i put it to make sure its right?
well you're concerned about the jump right?
So for example inside the if statement on line 37 would be a really good spot
Hey guys.. I have a situation here I am a bit stuck for the past 2h, and seems to be easy and I managed to make it work in another small game I made before. But now for some reason is not working. So I have a UImanager where I show text in the screem basically update the text in the UImanager with the actuall player exp.. when the player experience increase when I get experience in the map it works as the Debug.log I have after the player get the exp shows the exp is correct and it is increasing, but when I try after that increase to add that to the text in the UI doesnt work. ANy ideas just by looking to those SS ?
Put a debug log in UpdateExperience, log the value of experience after you set the text
Actually, looking at it, there's basically no way you don't have an error.
Check your console
i dont have error
Well, put your log after you set the text and show a screenshot of your console with that log showing
the debug log shows 0 always
so for some reason its not working
and That I already know
that is why I asked here why that could be happening 😛
Ah, wait, I missed the [SerializeField] sorry, I just woke up
all good 😄
and I am already in unity for the past 10h
so I might not be seeing something easy
to spot
i don’t understand the issue
it shows the wrong text, or it shows no text, or the text doesn’t change?
So it seems whatever Player your UIManager references has no experience. Either GetExperience does nothing or you're calling it on a different Player
also you shouldn’t store two values of exp that can get desynced
Or data.howMuchExperience actually is zero
hmm ok i will check it better thank you
if Debug.Log says experience is 0, then I would work backwards from why exp is 0
yeah I am trying to do all the path and see if the order is correct.
first, I would delete the experience field from the UI class
UI class should be reading EXP from a central spot
hmm ok, make sense
then go to the experience field for the player, and change it so you have a custom setter. Change the setter to give a Debug.Log whenever it gets called
in Ui Manager I am asigning the player EXP to the experience variable so I can show it on the screen
I know. Don’t save it as a field
UI manager already knows where to go read EXP because it has a reference to the player
now in the player’s exp, give it a setter to debug.Log
like
private int _experience;
public int experience { get => _experience; set { Debug.Log(“Changing exp to “ + value; _experience = value; }}
this way you get notified whenever EXP changes
you should use that setter anyway so your UI can just know whenever exp changes
example:
public event Action OnEXPChange;
setter: if (_experience != value) OnEXPChange?.Invoke();
then UI manager can just listen to OnEXP change, so it can get updated whenever that value changes
That is a bit advanced for me. But I will try thank you again !!
you should learn events/Actions. they will make your life easier
i will have a look into it for you. Thank you. I am going step by step otherwise I get crazy. But I managed to do it in another small game I was doing and worked in this one is not as its a bit bigger so prob is just a logic order that I am missing here
example;
public event Action OnJump;
public void Jump() {
OnJump?.Invoke();
}
}
public class JumpDetector() {
[SerializeField] private PlayerMovement move;
void OnEnable() { move.OnJump += WeJumped; }
void OnDisable() { move.OnJump -= WeJumped; }
void WeJumped() => Debug.Log(“We Jumped!”);
}```
understand?
yes understood now, Will try something here and let u know later if worked thank you again for your time
fixed, and the prob in my case not sure but I changed to that and fixed
instead of using serializedfiled and using the prefab on the inspector
it's the same thing so why is mine wrong
it's not the same
look again
when you do it the same, it will work
no I don't see
Look at every character
Do you see a comma in theirs after dir.normalized?
The quality is really bad so I can't tell, but are you using a ^ ?
Im a complete beginner in unity and im trying to make a simple clicking game with a cookie, i made a componenet for the cookie/coin and a script (using chat gpt) but for some reason the counter is not increasing even if i click on it
the script used:
using UnityEngine;
using UnityEngine.UI;
public class ClickerGame : MonoBehaviour
{
public Text clickCountText;
private int clickCount = 0;
private void Start()
{
// Initialize the click count and update the text.
UpdateClickCountText();
}
private void UpdateClickCountText()
{
// Update the UI text to display the click count.
clickCountText.text = "Cookies: " + clickCount;
}
public void OnClick()
{
// This method is called when the cookie is clicked.
clickCount++;
UpdateClickCountText();
Debug.Log("Cookie clicked! Click count: " + clickCount);
}
}
what's supposed to call OnClick?
code doesn't just run magically
is public void Onclick a function?
oh alright thanks
google "detect mouse click unity" or some keywords like this
p.OnClick();
ok thanks :)
if you don't have a pointer you cant point at stuff and click on it, you can move a pointer with a gamepad's thumbstick or you can use the EventSystem's Selectable system and contextual NavLinks. Usually you either completely separate mouse & gamepad control-scheme from each other or make a control-scheme that works for both with 1:1 input mappings, this means the mouse scheme would have not assume the existence of a pointer or you would make a joystick pointer for the gamepad scheme.
Hey, trying to wrap my head around this problem for an hour now: https://img.sidia.net/ZEyI5/juzexafA38.mp4/raw
My bullets slightly appear at 0, 0, 0
My source code:
Spawner
public GameEntity Instantiate(string resource, GameEntity entity = null, Transform parent = null)
{
[...]
var gameObject = Object.Instantiate(Resources.Load<GameObject>(resource), parent);
if (gameObject == null) return null;
var view = gameObject.GetComponent<EntityView>();
if (view == null)
{
Debug.LogError($"Spawned resource {resource} does not have entity script");
return entity;
}
view.Link(Contexts.sharedInstance, entity, resource);
[...]
}
Bullet
public override void Link(Contexts contexts, GameEntity entity, string entityName)
{
base.Link(contexts, entity, entityName);
var pos = _entity.position.Value;
var direction = _entity.direction.Value;
Rigidbody.position = pos;
Rigidbody.rotation = direction;
}
Do I have to Instantiate with a position for this not to happen? I never had problems first instantiating and then moving to my desired position without the object blinking at zero first
yes if you want an object to be instantiated at a specific position, you must instantiate them at that position
So its basically visible at zero for one frame if I dont?
that being said I don't really see the issue you're describing in the video
Look a bit left and up from where my character starts
got it
idk it's kind of unclear what's going on in this code
where does the Rigidbody reference come from
Its a public reference above, didnt want to paste my whole class as its a bit bigger
oh nvm I see it must be assigned in the inspector
Yep
A Physics.SyncTransforms() or transform.position = pos; may help too
Ill try
oof
I did either only rigidbody.position or transform.position
now i did both and it works like a charm
ill add in the velocity stuff again and look if it behaves as expected 😄
would be cleaner/more performant though just to instantiate it there in the first place
Yeah i guess I will edit the instantiate function to check if the entity has a position entityComponent attached and pre-position instead of doing that in the Link function of every view 😄
this is also a bit jank:
var gameObject = Object.Instantiate(Resources.Load<GameObject>(resource), parent);
if (gameObject == null) return null;```
gameObject will never be null here but Resources.Load<GameObject>(resource) might, and in that case you'll get an error
Oh, thanks, I'll edit accordingly
you can also just do Resources.Load<EntityView>() directly
instead of all the GameObject / GetComponent stuff
EntityView is the parent class for all EntityViews
Oh wait, thats what you mean
got it, ty
I got a question about memory
So since we can't contain contain references to a single bit, and instead must use BitArray, how many bits are used for each bit in a BitArray?
Sorry that's a mouthful, my goal is to have a barebones way of storing bits where each additional indice means 1 additonal bit in memory'
https://img.sidia.net/ZEyI5/dEjACEMO37.mp4/raw works like a charm with that change! thank you very much
C# uses 2 bytes/16 bits per bool, so a bool array isn't a favorable option either
Don’t use FindObjectOfType. You need to loop through all of the objects in the program to go find it, which is slow as fuck
ohh what is a better way?
you should get passed the reference in some way
GetComponent, or SerializeField, or a Singleton that has the reference
Please use a pastebin for large chunks of code
or a reference to something with the reference
How is your Player1/2Score defined?
!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 made a singleton class with references to common important objects, like the player character
more than 1 or 2 lines should be shared using a pastebin
FindObjectOfType is a big noob trap tho. Should avoid
!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'm using this script for letterboxing, but I can't get the aspect ratio to change during runtime
RescaleCamera() is called in Update(), so changes to targetAspect should apply in real time as far as I can tell
any errors in console?
also are you using Cinemachine?
bump
No errors, yes I'm using a Cinemachine 2d tracking camera
Manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0)
does it work on a basic camera (no cinemachine) in a scene on its own?
Reason why I'm trying to create a 5 byte array is in an effort to optomize memory usage of a voxel world
Each chunk is 32 by 32 by 32 so i only need 5 bit precision to describe any blocks position in a chunk
would prefer not to use any more than that if possible
bools use 32 bits each
public (GameEntity, EntityView) Instantiate(string resource, GameEntity entity = null, Transform parent = null)
{
entity ??= CreateEntity();
var loadedResource = Resources.Load<EntityView>(resource);
if (loadedResource == null) {
Debug.LogError($"Requested resource {resource} does not exist");
return (entity, null);
}
var position = entity.hasPosition ? entity.position.Value : Vector3.zero;
var view = Object.Instantiate(loadedResource, position, Quaternion.identity, parent);
view.Link(Contexts.sharedInstance, entity, resource);
return (entity, view);
}
This looks better now? or still something I should change?
Then use a byte[] and serialize your data like you want.
Also, it is 1 byte, not 4 byte.
Okay, testing revealed something. Aspect ratio will change, but not until the window is resized. If I try to change from 16/9 to classic 4/3, the letterboxes won't appear until I change the size of the window and that triggers a refresh
so I think I just need to add a || to the if statement that triggers updating the letterbox inside the script, probably
sizeof(bool) returns 1 at least
seems fine
How Can I get the damage int and mesh of the weapon I pick up from the weapon I pick up
In this script https://hatebin.com/gilbfmrtcn I only make the sword child visible and delete the one I pickup
Get a component from it when your ray hits it, then you can get whatever data you need from that component
but wouldnt that change the attributes of my current weapon when I look at another one
I have absolutely no idea about the rest of your game beyond what you have shown here
You asked how to get a value from the thing you pick up
I'm telling you how to do that
oh thanks I understood
but when I pick up it destroys the gameobject wouldnt that occur an error because there isnt a gameobject I can get the values from
Get the values before you destroy it
I'll try
I have found a script called CountDown which I do not remember making
Does anyone know why it is there? Is it something that is automatically there? I am thinking of removing it
I think you just made it and forgot 🤷♂️
Is there a namespace it's in?
Programming is like being a detective in a murder mystery in which you are also the murderer
Time for a git blame
SCRIPT 1
private new Camera camera;
private interactable Interactable;
[SerializeField] private Texture2D Cursor1;
[SerializeField] private Texture2D Cursor2;
private Vector2 cursorHotspot;
public void Start()
{
camera = GetComponent<Camera>();
cursorHotspot = new Vector2(Cursor1.width / 2, Cursor1.height / 2);
Cursor.SetCursor(Cursor1, cursorHotspot, CursorMode.Auto);
}
void Update()
{
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit hitInfo))
{
if (hitInfo.collider.gameObject.GetComponent<interactable>() != false)
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("tap");
if (Interactable == null || Interactable.ObjectID != hitInfo.collider.GetComponent<interactable>().ObjectID) //source of problem?
{
Interactable = hitInfo.collider.GetComponent<interactable>();
Debug.Log("newINT");
Interactable.onInteract.Invoke();
}
}
cursorHotspot = new Vector2(Cursor2.width / 2, Cursor2.height / 2);
Cursor.SetCursor(Cursor2, cursorHotspot, CursorMode.Auto);
}
else
{
cursorHotspot = new Vector2(Cursor1.width / 2, Cursor1.height / 2);
Cursor.SetCursor(Cursor1, cursorHotspot, CursorMode.Auto);
}
}
}
SCRIPT2
public class interactable : MonoBehaviour
{
public UnityEvent onInteract;
public int ObjectID;
// Start is called before the first frame update
void Start()
{
ObjectID = Random.Range(0, 999999);
}
}
I have been trying to sort this out for weeks and any help would be much appreciated, basically the interact will work once and will only work again if I interact with another object then come back to 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.
done
yeah you're explitly checking if it's the same object Interactable.ObjectID != hitInfo.collider.GetComponent<interactable>().ObjectID
the ObjectID thing is totally pointless btw
you could achieve the same thing with Interactable != hitInfo.collider.GetComponent<interactable>()
Ill give it a shot
i mean
that's not going to fix your problem
I'm just saying here's no need for that object ID scheme
since all of these objects already have ids
but the reason you can't interact twice is because you're doing that check in the first place
That object ID thing is pretty bad too. You will basically have a somewhat rare chance that your game breaks
why are you doing that?
not even that rare tbh
looks like in this case a rare chance that the game works properly lol
I also don't recommend doing hitInfo.collider.gameObject.GetComponent<interactable>() over and over again, it's a performance waster
basically this whole if statement if (Interactable == null || Interactable.ObjectID != hitInfo.collider.GetComponent<interactable>().ObjectID) should be deleted
there's not really any need for it.
But serialized filed was not working.. i can try GameObject player with serialized and see if works
So next problem for me... first time using World Space UI: https://img.sidia.net/ZEyI5/padepiQe40.mp4/raw
My healthbar is rotating with the monster, understandable that it happens, but whats the best way to fix it? If i put the NavMeshAgent on a child object to rather only rotate the mesh part the parent doesnt move at all anymore. I attached the structure of my Gameobject.
The only solution that worked for me was executing UI.rotation = Quaternion.Euler(30, 0, 0); on every Update but I feel like thats a hacky solution
im going to check if that works thanks
IT DID!!!
WHOOO
I am genuinly so happy rn
you should invest in learning some simple debugging techniques
you can solve these problems on your own
yeah i have been trying to learn that sort of stuff, but it never occurred to me the whole line of code didnt need to be there, I kind of just kept changing it
There's a class to add constraints to children to override the hierarchy rotations, otherwise add another parent/layer and make the text a sibling to the model.
Sounds like you were basically guessing randomly rather than taking a systematic and logical approach
thanks for the help though, very appreciated, I know its not much but would you wanna be in the credits?
Sure throw me in
story of my life
I cant make the UI a sibling to the moving object as its done via NavMeshAgent and that will always rotate the parent instead of just the mesh, didnt find an option to change that
Oh, you're using UI eh
Yeah, a World Space Canvas
Ok, similar idea I had, but remove the navmesh from the parent and go down a child. Basically the parent is just a wrapper, and now you can have a sibling relationship to the HP bar.
but, you want to then update the position manually through script
then the parent doesnt move anymore, only the child object
In the case i might aswell keep resetting the ui rotation, same effect as setting the position manually every frame 😄
The idea is to just update the rotation and position without having the hierarchy do it for you
or use this
https://docs.unity3d.com/Manual/Constraints.html
and basically make all hp bars rotate relating to an object that doesn't rotate (the game manager) ;)
I have a gameobject for my sword.its looking(mesh renderer) changes on conditions,but their rotations arent compatible ,like when rotation is 90 one is looking normal but other one does not look normal when it I put it in mesh renderer what can I do
Seems like the different meshes were exported differently, if you used a 3D modelling software
You'll have to re-export them with identical export settings
yes youre right
Hello!
I noticed that when I press a button and also check Input.GetKeyUp(KeyCode.Mouse0) in Update(), the button event gets called before the update where GetKeyUp returns true.
Do you think I can rely on that? (Will it always be in that order or is it random?)
I've got a zelda style hearts "life bar" to show health for a 2d game I'm working on. It starts as a single sprite, but is tiled and continuous. When I change the width, it grows to the left and goes off the screen, instead of growing to the right, and I was curious if this was something I could change in code (or somewhere else)? I'm setting the width correctly, I think... currentHealthRenderer.size = new Vector2(heartSize.x * fullHearts, heartSize.y);
Wdym by "the button event gets called"?
What button event?
when you expand its expanding from the center
The function I set here
Probably depends on where in the execution order the event system compares with your script. I wouldn't rely on it, no.
How do I get it to expand from the left to the right?
try chaning the anchor point to the left corner
Hmm ok, thank you!
I don't see an anchor in the inspector? Am I missing something?
What's the use case?
Oh
Anchors are for UI elements
It's not UI?
this is not a UI element
dang
Did you mean to make it a UI element?
Ahhh. It should be a UI element.
no wonder size is huge
You can make it work without UI, but then you're having to do some more manual work
Make UI > Anchor top-left, edit the Rect Transform's sizeDelta property
I figured it was something easy I was doing wrong.
Another idea is instead of tiling a texture, just make multiple gameobjects per heart
That seems memory inefficient... I guess it's not that big a deal since the max number of hearts they would have is pretty low.
We aren't. 😂
but i like minecraft
everyone likes minecraft
every game should start by trying to be minecraft
If your game isn't a single mesh with a single texture atlas then you're doing it wrong
So I've changed my sprite to an image... But I still have the same problem. And I'm not sure what that warning means...
That was it. Thank you! I thought the anchor you were mentioning was the top left corner, not the pivot.
yay 🙂
and yeah pivot and achor are diff purposes
I don't really understand the differences.. Was the thing I thought the anchor actually the anchor? (the part that says "top left")?
And is Anchor for deciding where the UI goes as you change resolution?
yea Pivot is the origin point of the Image/rect
Anchor is where this element will be stuck when you shift resolution
Got it. And the origin point of the rect is where it will grow from if you change the size?
pretty much yea
Thank you for the explanation! This has helped a lot. 🙂
doesnt matter
when I add a child to a parent gameobject it changes the transform axis of the parent
how do i prevent this?
What is it?
create the gameobject outside of the parent, then drag it in
when you create terrain it generates one of those. it just stores all of the terrain data.
this is what happens when i do that
the red circle parent starts with its axis in the center
oh its not actually changing the position
then when i drag the child in, its axis is now halfway between its own and the child's
its just changing the center
that's what i want to prevent
at the top, next to where it says "Global/Local", you should see "Center". change that to "Pivot"
Change "Center" to "Pivot"
thanks
Hello,
Does anyone know if i can use _LightColor0 in Shadergraph?
When i add property with same name, not exposed, it says redefinition of '_LightColor0'
Anyone know a way around this?
whoops!
hello, does anyone know any idea how to get a public float from another script in another game object. I've watched a lot of tutorials and yet can't find the solution to my problem.
- get a reference to the instance of the other script that you care about.
- access it via
theReference.theVariable
this is the most basic unity question asked hundreds of times per day. Those tutorials likely showed you many different ways to accomplish to part 1.
i will try
i am sorry but i am stupid kid and i don't know what else to do.
step one is to configure your IDE
!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
When I try to turn the cube in my touch direction it works, but the further i go the weaker the rotation is, the weird thing is when i delete the movement and let the rotation, it works fine.
Can you think of what the problem is?
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UIElements;
public class PlayerScript : MonoBehaviour
{
[SerializeField] private Camera mainCamera;
private Rigidbody rb;
private float speed;
private Vector3 tp;
private Quaternion toRotation;
void Start()
{
speed = 5f;
tp = Vector3.forward;
rb = GetComponent<Rigidbody>();
}
void Update()
{
if(Input.touchCount == 1)
{
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Began)
{
if (Physics.Raycast( Camera.main.ScreenPointToRay(touch.position), out RaycastHit hit, 40f))
{
tp = hit.point;
tp.z = transform.position.z + 5;
tp.y = 0;
print(hit.point);
}
}
}
toRotation = Quaternion.LookRotation(tp, Vector3.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, 6f);
}
private void FixedUpdate()
{
rb.velocity = transform.TransformDirection(Vector3.forward) * speed;
}
}
Right-clicking this and selecting Reload With Dependencies should be enough.
It detected both the solution and the project
i have 100mb space xd
huh?
You're using a position vector as if it were a direction vector. Quaternion.LookRotation(tp, Vector3.up);
that's incorrect, leading to your issue.
100 megabytes
Doesn't matter?
just sharing
Then make some room
so should i use transform.position - tp?
that will get you a direction vector
but not the right one
why not
well it all depends what you do with that vector now doesn't it
for one I think you should be using Plane.Raycast here - not Physics.Raycast
and then just make sure you project the look vector on the XZ plane before creating your quaternion
or make sure your plane you chose for Plane.Raycast is at the same y position as your player object
how do i project the look vector on the XZ plane?
i dont really understand the problem of the code
simple
it's making your object tilt up/down
then when you move "forward" it's moving up/down since it's tilting that way
by the way transform.TransformDirection(Vector3.forward) can just be written as transform.forward
but why does the turning effect gets weaker and weaker?
because of this #💻┃code-beginner message
you're just looking at a point further and further away from the origin
hence a more and more straight look vector
but in transform.position - tp it does it aswell
could probably just freeze the tilt rotation and the direction would be fine with the raycast
you'd have to show the code
because you're also doing this: tp.z = transform.position.z + 5; which is likewise nonsensical
freezing the rotation on the RB will do nothing when you are manually changing the object's rotation
this prevents it from going backwards
ah, right then probably just set it to 0 in the script, eh?
Is it the y that's tilting?
it does a lot more than that
it also makes sure the vector is completely wrong
because the z psoition of the hit is extremely important
and you are overwriting it
it just moves the z coordinate to a fix spot
you could clamp it to the player's position. But don't just blindly set it
the wrong spot, yes
actually Ok i see what you're saying
it can work
but you need to do the rest correctly
how xD
e.g.
toRotation = Quaternion.LookRotation(tp, Vector3.up);
needs to be something like:
Vector3 dir = tp - transform.position;
dir.y = 0;
toRotation = Quaternion.LookRotation(dir, Vector3.up);```
the plane.raycast could be a better way but with y = 0 im doing the same
dir.y = 0; is a poor man's way of doing the plane projection
hey now
oh true wait im testing
you're setting the position of the hit point, but the cube's y position is NOT 0.
So the direction from not 0 to 0 is up or down
no no its local
hence this
there's nothing local about it
everything here is world space
no
No it's not
yes
wait
maybe that's part of your confusion
guys let me talk
you see in the video that it doesnt look up or down
it works fine
Then write a whole paragraph 🤷♂️
that's correct except for the whole direction being wrong part
My example code shows how to do it properly
You don't
Start a coroutine inside it
OnTriggerEnter fires once when a collision begins
In previous Unity versions OnTriggerEnter itself could be a coroutine, not sure if that's still possible
I am trying to queue up some animations i have, one or more animations can get triggered in my game but i want to queue them up so they play one after the other, right now if more then 1 is tiggered, it randomly plays only one animation, anyone know how?
Really? Ive heard Start can be a coroutine, never about OnTriggerEnter, that sounds interesting
A special kind of function in Unity that lets you include delays (such as "wait one frame") inline in the code
Use a blend tree
Set them up in the animator controller so that one transitions into the next, with exit time being the only condition
Yeah check out the bottom of this docs page from 2017: https://docs.unity3d.com/2017.3/Documentation/ScriptReference/MonoBehaviour.OnTriggerEnter.html
yeah it works thank you
yes you can use deltaTime in a coroutine
you can use it anywhere you want
doesn't mean you'll be using it correctly 😉
hmm i can do it even tho i dont know which one is going to get triggered? if i have 9 animations and one or more randomly gets triggered depending on what happens in game, like a slot, depeding on what you win
So, you basically want them to play in a long loop, but you can start from anywhere in the loop?
Like A->B->C->A but you can start at any of A, B, or C?
So i have to use animation instead of animator in code?
I mean I guess you can use the animator blend tree but I'd assume it's going to be a giant spiderweb
If i have A, B, C, D, E, F, G as animations, depending on the game any of those can get triggered and more then one at the same time, if so i want them to queue
So, do you want G to go into A or does it always stop at G?
Oh, wait, I think I see
hmm, havnt used that yet, ill look it up
Lemme make a quick visual example, this is hard to explain in words
Can i link my game, its not published but you can still play it. And you will see what i mean
Like you see there, you can win if more then one symbol combo hits, and every combo has its animation but if more then one hits only one animation is played, so i want them to queue and alternate
Aight, yeah I see what you're doing. Just instead of repeating the same animation you should have some data struct you iterate over and play the next animation in queue.
Just check if the animation is playing, and if it's not then iterate to the next.
Okay, so, "Landing" is a state with no animation on it. It serves only as a redirect to the proper A, B, C, etc. and for them to transition back to. The transition into Landing is when any of them are true, and the transition to each individual state is when that trigger is true. The exits happen when the animation ends and goes back to Landing. This means that if another "Letter Parameter" is true, it goes to that one right away.
What you need hear is a boolean parameter for if any of them are playing, and an individual Trigger parameter for each one. Triggers are un-set when they're checked so they'll take care of un-setting themselves. Now, you can set the triggers while one is playing and it'll hop into that one when the current one ends instead of checking the trigger early and hopping right into it
yee if there are more then one animation to play, but if there is only one symbol combo win then its fine to loop that one animation
Damn thats a excellent visualization and explanation, thanks for that! I have to admit one thing tho, i dont really use animator like that, with parameters directly in unity, i use code instead, but ill have try that because that was a great explanation. I can just send what code i use:
void ChangeAnimationState(string newState)
{
//stop the same animation from interrupting itself
if (currentState == newState) return;
// play the animation
animator.Play(newState);
// reassign the current state
currentState = newState;
}
so basically i call a animation in my code where i want it, just wanted to show but ye thanks again
can anyone see whats wrong with this code? it was working until i closed and reopened unity 🤔
the code still shows the loading screen, loads the next scene and then hides the loading screen, however it doesnt wait 2 seconds
from what i can see everything looks fine
can I allow a method to begin only if a certain animation is playing?
nvm the loading screen was on the same sort order layer as the canvas in the next scene, so i couldnt see it
Technically you can do whatever you want
You could have the animation call that function
https://docs.unity3d.com/Manual/script-AnimationWindowEvent.html
would the line velocity += transform.forward * acceleration * Time.deltaTime;
increase "velocity" (which is a Vector3) gradually, or would it just set "velocity" to the value of "acceleration" since its a fixed int number?
acceleration would just be a speed here whoops didn't see you appending to the velocity so this value would be acceleration in this case, though the direction here seems pointless as the initial velocity should be set.
It's identical to
velocity = velocity + (transform.forward * acceleration * Time.deltaTime);
It can either increase or decrease
depending on the forward vector
and the acceleration
Well, maybe not increase or decrease since it's a vector at the end of the day
but it will change, that's for sure
Going forward with an acceleration of 1 for 10 seconds will give you something like (10,0,0) velocity
but turining completery right will just add speed to your right movement
it will still go at the speed of 10 forwards
Hm. Wouldn't this be a better way to implement momentum?
Well
It can certainly work
just do mind that the acceleration might skyrocket due to high framerate
adding a cooldown to increasing and decreasing the acceleration might be a good idea
Wouldn't adding "* Time.deltaTime" to "Ahead.z += acceleration" fix that?
But if you're using delta time then that is just as good I suppose
Yea.
But the rate of acceleration change is still higher in higher framerates
eh it should be constant
Well, I mean
probably give an example of what you're trying to do, cause now you have no direction
If someone were to balance an acceleration of 120 at all times and then stop accelerating
at 120fps it would drop to 0 in 1 second
at 60fps it would drop in 2 seconds
etc
could be possibly abused
either intentionally or not
Would that be preventable by adding a cool-down?
Yeah
or by adding a rate of decrease increase per second
Ahead.z += accelerationRatePerSecond * Time.deltaTime
easier than adding a cooldown
I see.
I'm pretty sure that's not necessarily? The idea of delta time is to prevent that exact situation, or maybe I'm not understanding something here.
Isn't anything that's multiplied by Time.deltaTime frame-rate independent?
I'm not talking about the position part, but about the rate of how the Ahead.z changes
Unless you mean instead of using low values of acceleration, you'd make it less frame dependent
Or unless my brain if fried after 10 hours of work
It might actually be alright and I'm just going in the wrong direction
Yeah, I think it should be alright.
Doesn't matter if the acceleration is 100 or 10000, deltaTime will take care of it
My bad.
Im using this simple script to download jpeg images from a server i have. But Unity sends this errors.
Alright.
Seems like the server you have doesn't return the image data compressed in either gzip or deflate, or the Content-Encoding header is not set in the response
Yeah its a server side issue. I tried with another image from another server and it works just fine.
If you have Postman or similar you could try querying your API to see what's different with that particular image
Or curl it directly into a file
Ill check on it. Thanks
Is there any way via the Unity editor to show values of fields or invoke methods of scripts without changing the code of the script (like serializing or setting stuff to public)? For ad hoc debugging purposes
Debug.Log for the former
Otherwise not really
That would be what i mean with chaging the script
I realize. I said otherwise not really
Bummer, but thanks 🙂
You can use the debugger. But that isn't with the unity editor
Sure. I was hoping for a more convenient and flexible way
You can invoke code through the editor with context menu. If you put the inspector on debug mode, it should show you private variables
Although context menu would require you to edit the script to include that line
Not what i was looking for, but interesting and good to now 🙂
Hi does anyone know how I can get my horror enemy to paterol around a house. Chase you if they see you and play a jumpscare once it get close enough to you
Yes, but explaining an entire major feature of a game is not something that can be easily typed. Learn about navmeshes to start.
Which thing do you not know how to do there
That's like six things, which one are you asking about
Make empty gameobjects for way points or a list of Vector3s. If at a waypoint, go to the other (or next if more than two). Do distance check on player and change move target to player if less than threshold. If less than second threshold "play jumpscare"
Is there an attribute to call [ExecuteInEditMode] on a single function?
I found some for runtime but couldn't for editor
Wdym? When do you want the function to execute?
Like I want OnEnable to be called in editor but would prefer to have only that function be affected by executeineditmode
in the future i'll probably approach it differently just trying to refactor this one step at a time
I guess there isn't a way to do that for one callback specifically.
But you could make a check in the other functions wether it's edit mode or not and return early if it is.
yeahhh
worst case i can do that
I have an enum for it but I think theres a small oversight in unity with prefabs that i gotta watch out for
Or just use OnValidate maybe?
nah instansiating gameobjects so no can do unless im mistaken
You could run the logic from wherever you're instantiating them then.
I'm instantiating them OnEnable 😛
Creating/Deleting parent objects for level design based hierchy organisation
Still don't really get it but ok. Sounds like you want an editor script though.
Mhmm perhaps
I didn't go that way since i didn't think there was any easy awake/onenable things but I guess I can probably do something janky with a bool and onscenegui
you can do #ifdef editor directive or w/e
#if UNITY_EDITOR
Func();
#endif```
pretty sure the compiler removes it on build
at least c++ compilers usually do
can someone guide me to getting my ide configuration to work. i followed some tutorials and idk what im doing wrong.
!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 dont follow. its all installed and i downloaded the game development for unity tab.
!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
why is my if statements get replaced with #if?
Show a screenshot. That is indeed odd
well idk why but its not doing it anymore. im really frustrated with this. its not autocorrecting.
idk i just followed some video tutorials and read some stuff on how to do it for visual studios
im using vs. and looking at the directions given i have done all of that
I mean this very respectfully because it's going to sound rude, If you did all of that it would be working
so you/we gotta figure out what step went wrong
Share a screenshot of unity workload installed and code editor selected in external tools.
What EXACTLY have you done?
Ok, that is one step. What else did you do?
No. It's in unity. It's covered in the guide, so go over it again.
If you need to do external tools, you didn't do all of it. That is one of the major steps
not to sound rude but i dont see it in the manual that was provided
its literally the first thing in the unity hub link and very slightly below the start of the visual studio download link
Well, share a screenshot then
Assuming that's really the same vs version you have selected in external tools, try regenerating project files.
ok i did, nothing really changed
Another thing to try is to delete the .sln and .csproj files from your project folder and reopen the visual studio.
wait, i went to visual editor in unity cause i figured u would have me check it and its locked, it was locked before but i unlocked it and i guess it relocked it. could that be why?
Wdym by "locked"?
What is visual editor?
The Visual Studio Editor package?
If so, remove the Engineering feature
It shouuuuld be fine with that version, but I dunno.
VS Code needs at least 2.0.20
Oh, the package. I don't think that matters. Not sure what "locked/unlocked" means but it seems to be installed, so it's fine.
oh...does it matter that i already uninstall engineering?
... Maybe..?
i hope not
Why would you uninstall it?
aethenosity said to remove it, so i did. but i reinstalled it. it seems to be a dev thing
but going back to ur other suggestion
how wouldi go about finding the .sln and .csproj file in my project folder?
The engineering feature installs editor packages for rider, vs code, and visual studio (and I think something else) but the packages are out of date and it locks them to that version. You need to uninstall it in order to update them.
That matters more for VS code though, which needs the second to most recent version
Just to clarify
been losing it over trying to find a way to do this:
do any of yall know a way i can rotate an object to be parallel to a collision?
im instantiating an object when my projectile object hits a wall, and i'm trying to make the instantiated object parallel to the surface the projectile collides with
Did you actually close and reopen the VS during any of the steps?
yes
Okay. Try right clicking the solution in the solution explorer and reload it.
How are you rotating it?
currently i've got nothing
i've got the rotating down with a quaternion euler thing down
but it's just, having it be in relation to the wall is messing with me
You can use the hit normal to orient your instantiated object.
cause i want to do it mathematically so it can apply to whatever surfacte it hits
mm ill look into that thanks
@teal vipersorry for not ussing the reply but i think were getting somewhere. its recognizing the monobehavior but i tried to make an if statement it went to #if again it says snippet, idk if that helps
Take a screenshot
wait
Of the whole window
nvm i thought i had it
It should show Assembly-CSharp if it's loaded correctly
This is working
You just need to fix the errors
semicolon after the basketball line and remove the test if
oh. wierd on my other computer it usually gives me the brackets and squiggly lines
but if its working ill take it
it is giving you squiggly lines
Well... it is showing squiggly lines there. What do you mean brackets?
no {} that one
ifs dont use that
Because if is not in a method scope
They do, after the condition of course. But they aren't necessary
It would only give you suggestions if they are correct in the context.
right
oh
see i wish i had my old computer it went out. and i had to get the other one. on that one it autofilled itself
or was that an add on or something like that
its not going to auto fill if it's not a valid place to use that
This one should autofill as well if configured properly (which it looks to be). It doesn't need any extension on top of that for autocomplete. Try making the if statement inside a method
you can't just put an if where you have it. That is not allowed in c#
What exactly did it autofill?
well an ex say i started with if.. it would the add () {} without having to type it
it was incredibly useful
This will do that
Did you try in a method like we said?
You have it OUTSIDE any method right now, as of the last screenshot
yeah its in the method its doesnt really do it like that tho
Screenshot?
It absolutely was not in the screenshot. You're saying you moved it?
well... yeah u told me to
You never responded. And it does should do autocomplete.... so.....
not really the if statement would fill similar to that but you wouldnt have to put anything in it would just auto fill () and{ } like so
They typed if and hit tab
it would show before pressing tab as well
In only typed "if"
im typing if and pressing tab and only getting if
Then you have some custom settings for all we know🤷♂️
got you
This is just a placeholder
You'd obviously need to type in your desired condition
It even autoselects true so when you type it removes it
okay i've finally got the hit figured out sorry about that, how would i go about rotating my instantiated object based off the normal (its a vector2?)
i done it with a guy in the discord and the way he instructed me was how i got it
probably should specify that i'm working in 2d ofc 😅
Well, we were not present there and you never told us what the guy told you so no clue...🤷♂️
its fine if it is custom ill figure it out.thanks for helping out as much as u did
The normal is a direction vector. You can assign it to transform.up/right/forward to make unity rotate the object accordingly, or get a rotation from it with Quaternion.LookRotatio or something.
quick question, im having a weird issue with instantiating a canvas, then immediately updating its values:
something like this pretty much, but this is producing some weird results
sometimes the overrideSorting or sortingOrder is unchanged
example 1 (where override sorting is not enabled, but the sorting order is properly changed to 3)
ok actually, figured out something weird?
if the parent canvas isnt enabled the frame i try this instantiation then it exhibits the weird behaviour
switching the override sorting/sorting order seems to half fix it
yeah, this weird issue got fixed by delaying the instantiation a frame later so that i can let the parent canvas enable, weird
Is best way to learn code make all code by yourself of just look at some assets that are make it your one?
code everything yourself: do not copy/paste. when you follow along with a tutorial. repeat the tutorial (a second time) by yourself to practice. read — and study — code from github repos. practice answering questions from unity discussions, forums, and discord servers . . .
and always go over the basics: type, reference type, value type, primitive (built-in) types, class, struct, interface, an instance, variables, methods, events, OOP, encapsulation, etc . . .
hi guys, how would I go about making a function that has "overloads", like optional arguments that I don't necessarily need to type in to use the function (as they aren't always necessarry). The one in my case specifically sometimes requires the use of a scriptable object
optional parameters go at the end of the method signature and must be assigned a value . . .
If you want an overload, you simply just write the function again with different parameters. That's all it is
Excuse me. I need a little help with my Animation
Why does it play and stop play and stop like this ? T-T
wow I had no idea it was that easy thanks!