#💻┃code-beginner
1 messages · Page 50 of 1
Hey guys, removed my camera, now added a new one.. and I had that in my code that is not working any more . how to fix that?
then the function is not getting called, figure out why not
wdym by "they did not work"?
Data is from the API response, gameData is from the Json file i've created
Is your camera tagged MainCamera
No - put it in the spot where you are confused about the code running that you don't expect to run
what do u mean they just did not work
that fixed ty
What does "not work" mean?
They didn't print?
Then the code you are looking at is not running at all.
no they printed
So it seems they did work after all
so then why would you say they didn't work??? That's why I asked.
reposted in general
wait so when they print they worked?
when they print it means the code ran
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
so, here
There is no 5
1 sec
you need to print currentTIme as well
also put it OUTSIDE the if
and use a different label for each thing so you know what's what.
whats that?
sadly i dont know what to put here
I've been making a platformer themed game built for the amazon fire tv, on a windows build the player spawns and everything but on the fire build the player doesn't spawn. Is there a better channel to ask this in?
Typically you'd want to do it before but... should be fine
simpler/more readable though would be:
Debug.Log($"Current time is {currentTime}. Sunrise time is {gameData.SunriseTime}. Sunset time is {gameData.SunsetTime}");```
praetor all the code ran but it is not letting me jump
when i have it higher then 300
@mossy arrow Make a thread. Your hand-holding requirements always end up flooding these channels.
how is it my fault when mostly no one can help me when my player is not jumping
There are people helping you right now
@wintry quarry When there is not internet the value of the Json is 0 for both vars... Therefore I suspect that either the Json is being loaded incorrectly or it is saved incorrectly... Or it is lost... Or it is overwritten... WHAT WE KNOW IS THAT IS A JSON FILE PROBLEM
where
Fen said I dont know
PraetorBlue stop helping me after when he said to use Debug.Log
you just showed a screenshot of a piece of code not running, how do you want anyone tel help you?
That's irrelevant. Make a thread.
I believe the last message was asking you to properly post your code and you didn't so this is on you
and i fix this
Go into a thread and post your !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.
The fact you don't understand how debug logs work after you were supposedly using them (with help) 10 days ago just shows you're not actually committed to learning, and hoping someone will solve your issues.
and it is still not working
I've been making a platformer themed game built for the amazon fire tv, on a windows build the player spawns and everything but on the fire build the player doesn't spawn.
i used debug and i know how it works
Any tips are appreciated
sounds extremely specific, so you'll probably have more luck on a forum or something where you can get more eyes on your question
@wintry quarry Do you know what could happen with it?
I don't want to be awfull... but i would like to know how to fixe it and what's happenning...
Hi again! I need some help. I'm making a 2D game. I'm trying to shoot a raycast, and find an object at THE END of the raycast not the first thing it hits. Is this a feature of unity? If so can someone help
awesome thank you
Anyone know how to instantiate as a child of an object
Instantiate can take a parent Transform for some of its overloads. Pass the object that needs to be the parent there
Two of them, the second and the last in this list
random.NextInt64()
why am i getting an error on this? trying to move a csharp project to unity
it says Random does not contain a definition for NextInt64
thanks
Because Unity has its own Random class
You need System.Random
Or using System; at the top
No, you're not
Oh, you might be actually
sorry for sending an image of text lol
But NextInt64 is only available for .NET6 and above
does unity not support it then?
Correct
shi
Unity's C# is over 10 years old
if i use unitys own random class, will i be able to use a seed so that its consistent
like how i can do it with System.Random
Not sure whether Unity's has one that can return a long (Int64)
But you can generate two int and bit-shift one to construct a long lol
i guess i can just combine two random int
yeah
lmao
i can do the seed thing right?
thanks for the help anyway
how do i disable the auto code snippet suggestions?
i couldn't find out what they're called
Presumably you can click the ... and go to the settings
but no idea, can't even tell what IDE this is
I presume it's intellicode https://code.visualstudio.com/docs/csharp/intellicode
this didnt work for me... "empty" is the object im instantiating and "grid" is the parent object. did i do something wrong?
Trying to instantiate a copy of empty under Grid's parent?
Did you want to parent to Grid, or Grid's parent?
The former, Grid is the one to pass
no, im trying to instantiate empty under grid, which is the parent if that makes sense
Okay so just pass Grid
pass?
Hi people! WTF is happening here? I am trying to check it a generic constructor parameter called initial (which in this particular case is of type Collider2D) is null and set the HasValue flag accordignly and...well it simply doesn't work and I can't understand why. These are screenshots taken in debug mode immediately after the HasValue assignment.
I can't understand why HasValue results to be always true regardless
What type are you using to pass into the constructor?
Like, not the type you are passing, the type you have declared that you are passing
it's a <T> for the parameter declaration
lol i had to combine 4 ints to get a ulong, becasue random.Next() returns a int which is signed, and i need a 64 bit ulong
very ugly code
So it's presumably constrained to Collider2D when you declare the type
Exactly
Hrm. No idea then. I thought it might be a Unity Null thing you're seeing, but if it's actually declared as a UnityEngine.Object subtype there should be no issue
No you can just generate 2 ints, bit-shift one, and then cast the result to ulong
At the beginning I was thinking "sure there is something stupidly obviously wrong that I am not seeing here" but then... I am staring and testing for almost one hour already. It seems to be something related to the parameter itself (by the way the debugger doesn't seem to be affected in the same way? more confusion)
yeah but int is signed, and System.Random.Next() returns a non negative int, therefore it will only be 31 bits
It has an overload for min and max value
Post the method, also your generic type parameter is constrained to at least UnityEngine.Object right? Essential if you're passing Unity objects with their fake null and the == operator overload
Does the constraint actually matter to force it to use the Unity equality?
It's constrained to Collider2D
I've not tested whether constraints cause that behaviour, or just the implemented type
Should be able to check by hovering over the equality operation, if you can navigate to its definition and it's the one in UE.Object then you're probably fine
Hope they at least mitigate this when they'll switch to CoreCLR, with a static abstract interface that forces the implementation of operator ==, so you can actually constrain to the interface type and be sure UE.Object's override is called
Not sure how to prove it, but I am quite sure that I am not using the right equality operator. I tried copying the body of the method and paste it instead of the method call and it works that way
It's something due to the parameter assignment maybe? But still I can't understand why the debugger says the result of the comparison is false and Unity still thinks it's true
I just tested it and it looks like you do have to constrain the type
!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.
Adding where T : UnityEngine.Object made it use the UnityEngine.Object equality
If it wasn't present then it didn't
Trying right away
Ok, can't try right away because the same thing is used somewhere else with an int
but anyway, I trust you
I'll think it throught tomorrow
Thank you guys
theres no Span<T>.Sort() in unity? 😭
Method is .NET5 and above only
Before asking, check the docs: search the method and scroll down to the "Applies to" section
it’s really nice that Unity never updates to later versions of C# or dot Net. I think it would be super confusing if we suddenly got more tools to work with, and that everyone would hate that.
File-scoped namespaces plz
plzzzz
hi does anyone know how to prevent date cheats?
please do not use php time servers.
api call :\
unitywebrequest
Weird sarcasm because they've updated multiple times, and are transitioning to latest as we speak
thanks.... ive been working that for weeks
but I had trouble using api call
would you mind describing what went wrong?
should be fairly straight forward
oh alright, so the method I majorly tried is using a php server to get time,
but it got wrong because I kind of disliked it
because it doesn't work when internet connection is bad 😦
so I seeked for other methods, and thats
how it begun
Also I used
<?php
$datetime = date("Y-m-d\TH:i:s", time());
echo '{ "datetime": "'.$datetime.'" }';
?>
but the timezone was different
and it was unstable
so it went 500 sometimes
is the game single player? does it matter if player cheats
if this is a networked/multiplyer game then the only real solution is to make sure whatever the player is trying to cheat to get is something that lives in a database / web application you operate
if it's a singleplayer/local game there's basically nothing you can do
if you need to design around the internet being offline (like if this is a single player game), then you shouldnt worry about it because there is no viable solution that wont negatively affect someone
what is the feature if you dont mind explaining? im curious what you would ever need the irl date for
!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.
Why does this script work on multiple items that are close, instead of one at a time? ```cs
RaycastHit hit;
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit, maxPickupDistance, ~IgnoreMe))
{
if (hit.transform.tag == "Door")
{
Door = hit.transform.gameObject;
if (Gamecontrols.GamePlay.Interact.WasPressedThisFrame() && Door.GetComponent<Outline>().OutlineColor == Color.white)
{
Door.GetComponent<Door>().enabled = true;
}
}
}
If two objects are close together it works on both.
Can raycast see two items at once?
RaycastAll can
Are you doing this every frame?
Yes
Check if your key was pressed BEFORE you do the physics stuff, its very expensive to raycast every frame
ok
Also there is better methods to check if you are looking at a door than to check for its outline color 😄
Span is just a reference to section of an array. 
I imagine that you would utterly change the array itself when you try to sort it.
Raycasts are super cheap, no?
It's the GetComponent that can hurt
Yes they are really cheap.
It's a common myth that they are expensive
I mean it can be an issue if you have hundreds every frame. But one is unnoticeable
Oh yeah sorry, still no need to even do the raycast unless the button was pressed
Oh forsure
I would do a raycast every frame or every couple frames to show tooltips and key prompts for what you look at
And then do a trygetcomponent only when you press a key
GetComponent is definitely lighter than a raycast.
Oh frl?
I feel like the vibe i've consistently got online was very much not that haha
Find functions might be heavier. But it all depends.
Get component just checks the list of components on the object. What is there to be heavy?
So then that explains it - two frames in a row
What is the best way to save variable data that needs to be accessed by a lot of scripts?
A singleton would be convenient.
alr i will look into that
is there a better way to store global variables?
What issue do you have with a Singleton?
If its very uncomplicated data, like a number, you could use static variables, but as the other 2 said, singletons are your best shot
ok
yeh i just used Span.ToArray() and ordered it like that
in the newer .net there is Span.Sort() though
which is what i was previously using
Now that defeats the point of spans. 
¯_(ツ)_/¯
isn’t a span like… an array the way arrays were always supposed to work?
A span is just a slice of an array that is always stack-allocated. Also allows you to take a slice of an array to work on without making a new array, or needing to do loops with offsets. Example from the docs:
var array = new int[] { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
var slice = new Span<int>(array, 2, 5);
for (int ctr = 0; ctr < slice.Length; ctr++)
slice[ctr] *= 2;
// The example displays the following output:
// 2 4 12 16 20 24 28 16 18 20
i thought arrays come from C, where you have a literal pointer to a spot in memory, and direct the computer to go over however many bytes to access different parts of the array
which only makes sense with contiguous blocks of memory
that's what an array is, yes
in C#, arrays don’t need to be contiguous
at least i remember reading that, and thinking that is weird af
i can’t find anything on it rn

Span isn't only stack allocated. You can implicit cast a managed array into a Span.
And NativeArray to Span. Span is a lower level array, that can reference any point in memory.
I mean to say that the span itself is stack allocated, since it's a ref struct.
They are contiguous in C# too. It's just that you can have an array of reference types that would point at different points in memory. But you can have that in C as well. An array of pointers.
that’s good. I’d rather it be like that anyway
There isn't really any way to implement an array differently.
There are linked lists, but they are not arrays
If you have an array of classes, you're storing pointers and you can bet it's mostly going to be random access
structs will be stored contiguously and you'll make good use of the CPU cache
hopefully that clears it up
oh. makes sense

How can I make a direct reference to an object without dragging it?
Via code.
When you instantiate something it returns a reference, and you can then pass that around.
Or you can get it through a singleton or something
Key is string and value is int
And you use index to access the values array which is ordered by key…
Ie it is “unordered” without considering key array
ty, was really confused until i research about sortedlist
Should have using something else to store user data and their score, not using database (Mysql) yet, just messing around
How do I change this to 1 using a script? that function is imported from FadeInOut.cs, and I want to change the value from other script ()Sorry for bad english, if you confused just mention me}
FadeInOut.cs
using UnityEngine;
using UnityEngine.SceneManagement;
public class FadeInOut : MonoBehaviour
{
public Animator animator;
public int levelToLoad;
// Start is called before the first frame update
void Start()
{
animator = GameObject.FindWithTag("FadeUI").GetComponent<Animator>();
}
void Update()
{
}
public void FadeToLevel(int levelIndex)
{
levelToLoad = levelIndex;
animator.SetTrigger("FadeOut");
}
public void OnFadeComplete()
{
SceneManager.LoadScene(levelToLoad);
}
}
Other Script
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class OptionsManager : MonoBehaviour
{
public OptionsDatabase optionsDB;
public TMP_Text nameText;
public Image artworkSpritePlace;
public Button StartButton;
private int selectorOption = 0;
private void Start()
{
UpdateCharacter(selectorOption);
}
public void NextOption()
{
selectorOption++;
if (selectorOption >= optionsDB.OptionsCount)
{
selectorOption = 0;
}
Debug.Log(selectorOption); Debug.Log(optionsDB.OptionsCount);
UpdateCharacter(selectorOption);
}
public void BackOption()
{
selectorOption--;
if (selectorOption <= 0)
{
selectorOption = optionsDB.OptionsCount - 1;
}
Debug.Log(selectorOption); Debug.Log(optionsDB.OptionsCount);
UpdateCharacter(selectorOption);
}
private void UpdateCharacter(int selectedOption)
{
Character character = optionsDB.GetOption(selectedOption);
artworkSpritePlace.sprite = character.LearningMaterialCover;
nameText.text = character.LearningMaterialName;
StartButton.enabled = character.enableStartButton;
Debug.Log(StartButton.GetComponents<FadeInOut>());
}
}
You can't change that value. What you can do is instead of passing the value in the inspector, call a method that retrieves the value and passes it to whoever needs to have it.
OKay thanks
NowI have another problem
How do I change a public variable from a script attached into a gameObject
scriptReference.publicField = newValue
I'd strongly discourage you from having public fields though. Use properties instead.
Okay Thanks, But is there any tutorial for properties?
and Is there anyway to get script named FadeInOut and change the leveltoload?
Yes. You can get a script with GetComponent.
I'd suggest going through unity basics, as this is all covered.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Alr found it, now I'm confused on how to get an object data
What do you mean?
public GameObject FadeS;
private object anj;
anj = FadeS.GetComponent<FadeInOut>();
Debug.Log(anj.levelToLoad);
This will produce error
I am quite literally losing my fucking mind rn oh my g a w d
Why is anj of object type?😅
Let's start from reading the error and understanding it
So Im trying to make code that executes a win condition. I'm currently in college and we did this in class and it works perfectly. I basically copied the code from class into my project and it doesnt work for some reason. Almost everything is the same logic wise and I am genuinely so confused. ```public class GameManager : MonoBehaviour
{
public void UpdateGameGoal(int amount)
{
enemiesRemaining += amount;
if(enemiesRemaining <= 0)
{
door.DoOpenDoor();
ExitDoorCondition();
}
}
}
public class TempEnemy : MonoBehaviour, IDamage
{
void Start()
{
GameManager.instance.UpdateGameGoal(1);
}
public void takeDamage(int dmg)
{
StartCoroutine(FlashRed());
Hp -= dmg;
if (Hp <= 0)
{
Destroy(gameObject);
Debug.Log("Die object Die");
GameManager.instance.UpdateGameGoal(-1); //This code gives me an error. If I remove it, everything is fine but I need this here
}
}```
What should I set it into?
enemiesRemaining -= amount; maybe? or du you pass in a negative value when calling UpdateGameGoal()?
You need to tell us what the error message says
Does GameManager have a static instance field?
no bc its not an instance
Let's start from reading the error.
But you are trying to access it right on that line.
NullReferenceException: Object reference not set to an instance of an object
Also "because it's not an instance" really doesn't justify anything.😅
what do you mean by instance
wait im getting my terminology mixed up i thought you meant interface 😭
Assets\UI\Selection\OptionsManager.cs(46,23): error CS1061: 'object' does not contain a definition for 'levelToLoad' and no accessible extension method 'levelToLoad' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
I though c# is the same as JS so i tried getting the value of levelToLoad from its keys 😭
Also yes it does
yes it has a static instance field my bad lol
You don't have an object in the scene that has the GameManager component
Okay, here's a tip for future. When you're asking for help, don't omit relevant code.
Why is the gamemanager supposed to get destroyed?
Ok, so do you have a gamemanager in the scene?
C# is a totally different language.😅
For starters it's strongly typed language. The error means that the "object" type doesn't contain your field.
i see where my issue may lie
1.So what should I fix 
2.SHould I change the var type from object to what ?
ok so i added the manager into the scene and its doing the same thing. when i shoot the enemy down to 0 hp, the enemy gets destroyed and its supposed to update the game goal
but its just throwing an error, the same one
You should go over C# basics.
You need to make sure your variables are of correct types.
- What type contains your field?
It works in my other project just fine but not in my personal one.
lemme get it
public GameObject FadeS;
private object anj;
anj = FadeS.GetComponent<FadeInOut>();
Debug.Log(anj.levelToLoad);
You should learn c# basic first…
like this is my code from the first project ```public void UpdateGameGoal(int amount)
{
enemiesRemaining += amount;
if(enemiesRemaining <= 0)
{
YouWin();
}
}
public void YouWin()
{
statePause();
menuActive = menuWin;
menuActive.SetActive(true);
}```
its virtually the same so i dont understand
Yeah looks like I should, because i fcked up
I'm sure that's not the whole code.
Js hides the concept of variable type
And you really should listen to my previous tip.@junior seal
its the whole code thats causing the error
what tip dude
i didnt see that. my bad
Where do you set the “instance” of game manager
Based on the shared code, it doesn't even exist.🤷♂️
can i share pictures?
Yes, but not if it's code...
Ya C# expects quite a bit more from you than JavaScript. Honestly though general programming concepts are transferrable between most languages. If you have JS experience and can get the c# syntax down, the rest should come easy.
!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.
Game Manager: https://paste.ofcode.org/xgyuGEkNfyNyrZTNi3GLwf
Temp Enemy: https://paste.ofcode.org/Tz4WZuxmCQNPuxTzxyit5V
When you get the error, pause the game, select the game manager in the hierarchy and take a screenshot of the whole editor with the console visible~
scratch that. Just show the entire error message
I'm guessing the error comes from the GameManager method
If it's deleted it won't throw that error
ignore that its not being deleted
The line number doesn't match but I'm guessing line 28 in your actual code is door.DoOpenDoor();
Probably not sharing the whole up to date code again😅
Okay, then make sure that there are no compile errors
i just didnt look at the scene stuff right
line 28 in my game manager code?
enemiesRemaining += amount;
Can't possibly throw that error.
well its telling me that??
Take a screenshot of the whole console window
Yes. The error message says that something is null on line 28 of GameManager.cs
Not possible. Make sure the updated code is compiled properly.
i have done that 3 times dude
How did you do that?
im telling you when i delete line 30 my Temp Enemy code that error doesnt happen
Are here to argue or accept help?
listen dude im here to get help but youre being a dick and not listening to what the fuck im saying. youve been insinuating that im stupid and cant understand basic fucking english. thats just fucking rude. Ive been trying to tell you that I have done this EXACT SAME THING before and it worked perfectly but RIGHT NOW it is not working for some ungodly reason.
Now can you please stop treating me like im a 4 year old who cant understand what youre talking about?
I don't know what you've imagined, but not once have I called you any of the words that you mentioned.
thats why i said insinuated
remember this???
basically saying im stupid
im not here to argue. Im frustrated as fuck so Im sorry but I dont like being talked down to
Lol what? How is that related? If I want to call someone stupid I would say that directly.
Anyways, if you don't want to provide the relevant information, I'm not sure we'll be able to proceed anywhere.
You call a method that can cause NRE doesn’t mean the action of “calling the method” give you NRE but some codes inside that method give you NRE, so delete the call of method is ofc remove the NRE, you dont even execute the code (inside that method) which causes NRE
Btw log if the instance is null and the door is null first
Again, im frustrated as I have been in the hospital all damn day, and now i have to do this and im getting talked down to, so yea im sorry dude. im trying my best. im sorry if my best isnt good enough but i thought this was a beginner friendly channel
considering the name
Well, a NRE is impossible on that line 28.
Im not expecting anything extraordinary. Just to share relevant info without saying stuff like "I checked million times".
Start from showing the console with the error. The whole window.
Okay. Now find the script file in your project window, select it and take a screenshot of the inspector.
Counting the lines manually, it seems like it's different from what you've shared previously.
Screenshot you code in ide including the line number next time
dunno why, thats exactly what i have
i was told to not do that
Now you can do that.
okay
You can screenshot your code if someone ask you to do !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.
You didn't save the file
ah shit thought i did
I remember the rule is stated somewhere but i forgot…
Hey guys, I have an object that is the enemy and it contains a Circle colider. If i want with code while 1 enemy is approaching other to detect that the other one is there and maintain distance, can I apply another collider and make it bigger to do the check or need to be all in code?
Yep. Now it makes sense.
Now, what can be null on that line?
i guess door?
bc the other is a function
Yes. That's a declaration of the variable. Not assignment/initialization.
You say "this thing is going to point at some door" basically. But you never assign any specific door to it.
okay well how do i assign that to a specific door in my scene
Many ways. You could use one of the Find methods. Or pass the door reference from somewhere else(the door itself for example).
im not very familiar with doing that so do you have any resources or advice?
https://unity.huh.how/references would be my suggestion.
That's to this specific issue, but I suggest going over some C# basics too.
oki thank you
Can someone help me with this, I have thirst bar and hunger bar and it goes down troughout the time and when it reaches 0 it will take ur health slowly but when u pickup some food it will give you amount depends on food or water u picked up but problem is as u can see in screenshot i give it an exact value but when hunger is still high like for example 80 and i add 50 to it it will be 130 and max is 100 so can someone help me add amount that will add up to 100 if it is left more than 50? This is script for thirstbar and hungerbar and screenshot is in player script:https://hastebin.com/share/omoqoxoqez.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
instead of
public float hunger = 100f
use
public float _hunger = 100f;
public float hunger {
get { return _hunger; }
set { if (_hunger + value < 100f) _hunger += value; else _hunger = 100f; }
}
do the same for thirst
this?
what do you think?
its good but what should i change here
nothing
Well
so now it should work
do you not understand the code I wrote?
This is a pretty rough way of handling something like this. All the tags and if statements...
Is this all in the player script in something like OnTriggerEnter?
Irrelevant to the question asked
{
this.grounded = Physics.CheckSphere(groundCheck.position, groundRadius, ground);
this.Look();
}
private void Look()
{
float axis = Input.GetAxis("Mouse X") * this.sensitivity * Time.fixedDeltaTime * this.sensMultiplier;
float single = Input.GetAxis("Mouse Y") * this.sensitivity * Time.fixedDeltaTime * this.sensMultiplier;
Quaternion quaternion = this.cam.transform.localRotation;
this.desiredX = quaternion.eulerAngles.y + axis;
this.xRotation -= single;
this.xRotation = Mathf.Clamp(this.xRotation, -90f, 90f);
this.cam.localRotation = Quaternion.Euler(this.xRotation, this.desiredX, 0);
transform.localRotation = Quaternion.Euler(0f, this.desiredX, 0f);
}``` why is this choppy? its a first person camera rotation based on mouse thing
i understand that if thirst is lower than value it will add value but if its bigger it will add it to the max
I know but I feel like tossing the guy a complex looking property setter isn't as helpful as cleaning up the code a bit and using Mathf.Clamp(0f, 100f) in some "ChangeHunter" method.
no, look at the code again
this is wrong
yes
but now my hunger and thirst never go down for some reason
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
_hunger -= Time.deltaTime * hungerSpeedMultiplier;
or
hunger += -(Time.deltaTime * hungerSpeedMultiplier);
The setter should be
set { if (value < 100f) _hunger = value; else _hunger = 100f; }
no
no, you need to check the result of the add
^ The setter doesn't do addition
now it works thanks
@golden ermine Hey want to know how to have a ton of different types of hunger/thirst pickups without needing to make a new tag + code it?
sure
Can I see what this entire method looks like?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
public void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.tag == "Pickup")
{
pickupSfx.Play();
}
if (collision.gameObject.tag == "PickupHeal")
{
healSfx.Play();
}
if (collision.gameObject.tag == "PickupHunger")
{
playerUI.hunger += 50;
eatSfx.Play();
}
if (collision.gameObject.tag == "PickupMidHunger")
{
playerUI.hunger += 35;
eatSfx.Play();
}
if (collision.gameObject.tag == "PickupLessHunger")
{
playerUI.hunger += 20;
eatSfx.Play();
}
if (collision.gameObject.tag == "PickupThirst")
{
playerUI.thirst += 50;
drinkSfx.Play();
}
if (collision.gameObject.tag == "PickupLessThirst")
{
playerUI.thirst += 20;
drinkSfx.Play();
}
if (collision.gameObject.CompareTag("Wood"))
{
woodSfx.Play();
playerUI.woodCount++;
}
}```
Ok so in this method I see you're checking what the player collides with and doing things based on the item, right?
What if you flipped it around? Have the item check for collision against the player. Then the item makes changes to the player (increases/decreases hunger etc).
You wouldn't need to create a tag for each item.
yea you are right that would be easier
{
this.grounded = Physics.CheckSphere(groundCheck.position, groundRadius, ground);
this.Look();
}
private void Look()
{
float axis = Input.GetAxis("Mouse X") * this.sensitivity * Time.fixedDeltaTime * this.sensMultiplier;
float single = Input.GetAxis("Mouse Y") * this.sensitivity * Time.fixedDeltaTime * this.sensMultiplier;
Quaternion quaternion = this.cam.transform.localRotation;
this.desiredX = quaternion.eulerAngles.y + axis;
this.xRotation -= single;
this.xRotation = Mathf.Clamp(this.xRotation, -90f, 90f);
this.cam.localRotation = Quaternion.Euler(this.xRotation, this.desiredX, 0);
transform.localRotation = Quaternion.Euler(0f, this.desiredX, 0f);
}``` why is this choppy? its a first person camera rotation based on mouse thing
Time.fixedDeltaTime why are you using fixedDeltaTime in an Update?
the same thing is still happening
Here's what I would suggest:
- Give the player methods like "Eat" and "Drink" and "CollectWood". These methods take in a float and update those stats based on the value given. They can even update the UI here.
- Create separate scripts for "HungerPickup", "ThirstPickup" and "WoodPickup" that check for collision against the player and call one of those methods. You can give those scripts a public float called "hungerValue"/"thirstValue"/"woodValue" so you can set the amount they give in the Inspector as opposed to needing conditions for all the different types of pickups.
actually its worse than before now
thank youu
Oh, this is from that jank Youtube tutorial again right?
Just make sure you are actualy following what he wrote, but I remember other people having problems with this tutorial as well.
im just writing what i remember it being like
but i changed it to normal deltaTime then back to fixedDeltaTime and now its working so that was weird
just for clarity, for Eating you could do this on the player class.
public float currentHunger;
public void Eat(float hungerValue)
{
currentHunter += hungerValue;
currentHunter = Mathf.Clamp(currentHunger, 0f, 100f);
playerUI.hunger = currentHunger;
eatSfx.Play();
}
Do this for Drink and Wood collecting as well.
and for the pickup you can just do
public float hungerValue;
public void OnTriggerEnter2D(Collider2D collision)
{
PlayerMovement player = collision.GetComponent<PlayerMovement>();
if(player != null)
{
player.Eat(hungerValue);
}
}
how would one go about moving an object along a 2d line driven by a float? 0- bottom corner, 1 top corner
the line being a bezier curve
It's not a just a "line" it's a curved line
You'd use bezier curves like you mentioned
Depends. Lines are typically defined by a series of points or mathematical functions. Usually the "best" way to do it is to define the start and end of the path as a 0 to 1 range and lerp along it.
I think there's a package for working with bezier (and maybe other) curvres
Hi Friends. I am using this code here to detect and make sure the enemies dont get too close together and overlap.. but if I stay in the same position they eventually overlap each other.. anyways to prevent that? thank you !!
// Find all nearby enemies within the detection radius.
Collider2D[] nearbyEnemies = Physics2D.OverlapCircleAll(transform.position, detectionRadius);
foreach (Collider2D enemyCollider in nearbyEnemies)
{
if (enemyCollider.CompareTag("Enemy") && enemyCollider != this.gameObject)
{
// Calculate the direction to the nearby enemy.
Vector2 direction = enemyCollider.transform.position - transform.position;
// If they are too close, move away from the other enemy.
if (direction.magnitude < avoidanceDistance)
{
// Move away from the other enemy.
Vector2 avoidanceDirection = -direction.normalized;
transform.Translate(avoidanceDirection * Time.deltaTime);
}
}
}
}
You probably want the "repulsion force" to scale based on the proximity, so that the closer they are, the faster they are pushed away.
Is giving them a small collider not an option?
they have it already but with is trigger on because if I shoot with my player
they die
and dessapear
Or just use an actual collider like I said in #💻┃unity-talk. But you could indeed fix this mathematically.
Wouldn't it make more sense for them to have a regular collider and give the bullets the trigger?
oh i thought both had to have the trigger..
nah
I can't remember the specifics but at least one of them just needs a rigidbody for the trigger to go off
yeah i unticked the is trigger to off and still works when i shoot them. BUT, they still overlap. Maybe I should increase the size of the collider? I mean its a collider they should not overlap it.
if you're moving them with transform.Translate they'll overlap
Translate is like a teleportation
ohhh.. what other way to move them if not with translate?
if you want physics interactions you're going to need a rigidbody, and you'll be moving it with rigidbody.velocity or rigidbody.MovePosition or rigidbody.AddForce
got it, thank you I will have a loot into this
Make sure you use the 2D version and not the 3D version, they are different.
got it
will try here to change it to that instead of using the translate
rigidbody takes the form of the sprite?
no
hmm ok.
well I'm not sure what you mean by "takes the form of"
actually didnt make sense my question, nevermind 😄
ok as it is now its working but it is moving very slow.
How can I change the speed? I know it would be in the MoveDirection
variable, but I am not sure, maybe put at the end *2
or somethying like that?
You can just multiply the vector by some arbitrary number. Now you have a MoveDirection vector with length 1, multiplying it to something is fine.
Tried like that Vector3 MoveDirection = _player.transform.position * 5 - transform.position * 5 ; or this Vector3 MoveDirection = (_player.transform.position - transform.position) * 5;
none worked, what Am I doing wrong?
you're multiplying before you normalize
do you know what is normalize?
I read it on documentation but still didnt understand it
fully to be honest
can I do it like that? rb.velocity = MoveDirection * 5 * Time.deltaTime;
or i dont need time.deltatime in rb ?
it will set the magnitude of your vector to be one
So delta time is more used to translate ?
ahh ok
working now. Thank you very much !

no. it's to convert something from units per frame to units per second
that should work just fine
I am sorry my mistake i had it serialized fiel
and was trying to change it on code again
and not on the inspector
now works changing on inspector
Even tho now using rb.velocity they still overlap
not as much maybe
increase the size of the collider then
but them when I shoot the anemy it will check the collision for the bullet way before it should
maybe do like Micro jackson said
use a child and put a collider on it to check for the bullet impact
would work right?
What I don't understand is why the 2 need to be a different size. They are circles, it should work fine with it being the same size.
but the prob is that they are overlaping if I use the same size as the sprite
using translate or rb.velocity
both ways to move
Then that is the problem, colliders can not overlap and you need to figure out why it does that.
Is the collider still a trigger on the Enemy?
Do you still have Translation code somewhere for the Enemy?
enemy the trigger is set to off
no i dont have any other translation code on the enemy anymore
You sure your not using the 3D collider?
yes I am sure
so using a child with a bigger collider just to try and avoid that would fix as you said no?
Perhaps, I don't understand why it doesn't work now. Maybe you get the exact same problem you have.
hmm ok i will review my code again shortly and let u know if I figured it out 😄
just finishing some work stuff
Good luck, going to nom some lunch 
enjoy ur meal
well here at the end of this code snippet I still have translate to move away from each other.. could it be the prob? tried to change it to rb.velocity but didnt work its breaking and they are not moving even very far away from each other.
I think I followed the guide correctly but my player still pass through the cube what did I do wrong?
I want to move the camera with my mouse ingame that my mouse keeps staying on the same object but the camera moves faster in the other direction why is this?
if(Input.GetMouseButtonDown(2))
{
currX = 0;
currY = 0;
lastX = 0;
lastY = 0;
}
if(Input.GetMouseButton(2))
{
print("Mousebutton");
currX = Input.mousePosition.x;
currY = Input.mousePosition.y;
if (lastX == 0)
{
lastX = currX;
lastY = currY;
}
if (currX - lastX > 0)
{
transform.Translate(Vector3.right * (currX - lastX) , Space.World);
}
else if (currX - lastX < 0)
{
transform.Translate(Vector3.left * -(currX - lastX), Space.World);
}
if(currY - lastY > 0)
{
transform.Translate(Vector3.forward * (currY - lastY), Space.World);
}
else if(currY - lastY < 0)
{
transform.Translate(Vector3.back * -(currY - lastY) , Space.World);
}
lastX = currX;
lastY = currY;
}
(its in an update loop)
your player has no collider
i see thanks
i was talking to @faint tulip sorry
np
ah sorry
shouldn't need a collider though, your CapsuleCast() must not return the correct value
i wrote it down like this though
float moveDistance = movementSpeed * Time.deltaTime;
float playerRadius = 7f;
float playerHeight = 2f;
bool canMove = !Physics.CapsuleCast(transform.position, transform.position + Vector3.up * playerHeight, playerRadius, movementDirection, moveDistance);
//if statement to make it move
if (canMove)
{
transform.position += movementDirection * moveDistance;
}
i have thos code to try and prevent things from going off the grid but it for some reason doesnt work but after going back in the grid and out on the other side then back then it works
i can take a video too if that helps, just need a recommendation on a program
you shouldn't use == for floats,
also when using floats (numbers with values after the '.' like 2.5 you need to put an 'f' behind them to mark them as floats, so: 3.75f
Try using currentPosition.y >= 3.75 && ...
anyone worked with configurable joints? I'm dealing with a problem when setting the target rotation. I got some code from ml-agent walker joint controller, though it seem the forces applied have no effect. Are there common mistakes when using them or should i share code? Thank you!
i added the f's and currentPosition.y <= -3.75f on the second one and now it doesnt go up but it still goes bellow returning this
show your code
these errors keep popping up in the console and i can't run the game
"An error occurred while resolving packages:
One or more packages could not be added to the local file system:
com.unity.settings-manager: EINVAL: invalid argument, futime
"Library\PackageCache\com.unity.testtools.codecoverage@1.2.4\Editor\CoveragePreferences.cs(31,19): error CS0246: The type or namespace name 'Settings' could not be found (are you missing a using directive or an assembly reference?)
"
does anyone know to fix it?
i dont have to put f behind the 1 do i?
theirs a whole list when i just started as a junior programmer
are rigidbodies a good way of keeping tight platformer controls?
you should try to change both the == 1 to something like >= 0.5f
I'll give it a try
Hey why is there no skybox in my game? The light is strange too, I'm using HDRP
this is a code channel
Ah sure
hi! has anyone built on a mac? I am stuggling to build on a mac
this is related to code. I am getting specific errors.
Then post them, we are not mind readers
thanks. see the image above. I downloaded different pluggins (xcode, visual studio for mac) as other forums suggested but still no luck
yeah. do you know how to get it? I thought to get it I needed bunch of entensions but no luck (i.e. xcode, visual studio for mac, etc)
Did you restart after installing it? It could be just a matter of environment variables not being updated.
yeah I did restart a few times.
Then not sure. I'm not really a Mac person.
yeah. same here 🙂 only trying to buid on mac so mac users can play my game
Hello! I have to survey 20 people for an assignment about AI programming: https://forms.gle/MwwmmUMg16HitJTU9
It would be kind of you can fill in the form for me, thanks!
I don't think there's the right place...
Does anyone know how to make camera tilt when turning left or right?
you haven't told us what platform you're trying to build for, what version of unity you're using, whether you're using Mono or IL2cPP, ...
I presume you're building on a mac for macOS, but that also could be an x86 macbook or an ARM macbook
I see that it's complaining about the Burst compiler failing to run.
I'm trying to auto-scroll my scroll view content to the bottom of the scroll view after I add a message to it, but I can't seem to get it working.
I tried referencing the ScrollRect and setting it's verticalNormalizedPosition to 0
I also tried setting the Scrollbar's value to 0
is the content rect change its size?
I have unity 2019.4.4f1. I am building for MacOS and have a mac book pro with M2. I am ussing IL2cPP. Note, I am not a mac user and created the game on pc and built on PC successfully.
Does a Mono build work?
Oh it seems to work if I wrap it in a coroutine like so.
public void PassPhrase(DialoguePhrase phrase)
{
AddMessage(phrase);
StartCoroutine(ScrollToBottom());
}
public IEnumerator ScrollToBottom()
{
yield return null;
ScrollView.verticalNormalizedPosition = 0;
}
So I guess I have to wait a frame first? That seems odd though, the Message GO is already instantiated by that point. Is there not a better work-around?
building. lets see.
A coroutine needs to have a yield if that's what you are asking. Not sure why you make this a coroutine atm.
the content rect does change even without waiting a frame first.
I'm yielding null to skip a frame here, which seems necessary if I want the scrollview to scroll to the 'new' bottom
i remember vertical layout group+content size filter need one frame to update itself, but i am not quite sure
Hard to tell without more info. Maybe share code and more details
idk if this applied to all the ui elements
that might be it then, that seems pretty wasteful though right? like this coroutine isn't going to do jack performance wise, but still.
Perhaps try in LateUpdate? If it updates everything in Update that should work is my guess.
it's not an update-tied call unfortunately
unless I start checking for content updates each frame but that seems even more wasteful haha
You can try WaitForEndOfFrame instead of waiting for a whole frame too
that works fine too. maybe i should look into an onsizechanged for the content fitter or something.
!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.
SetTargetRotation is the function used basically, i do se the values changing in the inspector though the joint doesn t seem to move. (I had values for spring and damper). Though, changing the target angular velocity works, but it is a hard method for an AI to control his limbs properly.
Show the inspector of that joint
Looks like your code is changing Slerp Drive but the joint is using X and YZ instead of slerp
I mean the Rotation Drive Mode
so should i change it to slerp?
That's what your code seems to be using, yes
nothing's changed
A lot of things could be wrong, configurablejoints are pretty complex
Start by posting your code correctly, see !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.
darn no luck. mono doesn't work either. do you know what I need to do to install library c? maybe I am missing some tick mark or pluggin.
may I ask why not build for mac on a windows machine?
Have you set up the limits correctly? Does it move if you change all the Angular limits to Free?
And obv make sure the rigidbody (or its connected body) is not kinematic
Seeing these values while in playmode could be helpful
i tried this, also the connected body are not kinematic
I was told it was impossible. Of course, I tried as well and it gave me an error. Is it supposed to work on windows?
something like this
i do change the force and the target rotation each frame
Why is it still using X and YZ
also with slerp it doesnt move
That wont work if your Angular X Drive and Angular YZ Drive have no zero spring
I just select macOS in the builder and it works for me
im trying to tilt my mesh when steering left / right and when i stop steering it tilts to normal again
if(Input.GetKeyDown(KeyCode.D))
{
current_Mesh_Rot = mesh.rotation.eulerAngles.x;
if(current_Mesh_Rot < 15f)
{
current_Mesh_Rot += 0.125f;
}
}
else
{
if(current_Mesh_Rot > 0)
{
current_Mesh_Rot -= 0.25f;
}
}
somehow this does nothing
Let me build it on the pc and show you the error. Maybe I need to enable something for it to work
Does the same error fall out?
I don't believe you can do an IL2CPP mac build on Windows
but I've definitely seen the mac mono option on my PC
that didnt work but i did this and now it worked
so for some reason its off by a super low value
Yes exactly the same
Yup that’s the error il2cpp. So you think I can try to build mono on pc and it should work? Does it change anything for end user?
IL2CPP can give better performance.
But Mono is still a lot better than no game :p
I'm not sure if you can build for both ARM and x86 from a PC. I haven't thought about that.
Did you try larger spring values? 1 is usually really low
Like crank it up to 50 to see if it does anything
Haha 😆. I guess when you transfer your game from pc to mac what changes do you need to make? I installed Xcode, burst compiler, and Visual Basic developer extension. Maybe I am missing something?
i'm not sure how you "installed" the burst compiler
do you mean you installed the Burst package?
visual basic is definitely irrelevant here
I already had the XCode command line tools installed, so perhaps those are necessary for building games.
that was it brother
now it works
thank you so much
Yes, burst package. Hmm I just have xcode installed. I don't see the command line tools. Is that a special extension?
If Burst is not a dependency of a package you've installed, and you have no code that uses Burst, then there's no reason to install the package
the command line tools give you things like the LLVM compiler toolchain on the command line
rather than as part of XCode
Some systems require these to be installed, so that they have a compiler to work with
Awesome
I am looking at the manual and don't see any mention of this
however, this page doesn't exist for unity 2019.x https://docs.unity3d.com/Manual/macos-building.html
Is the command line tool an application? I can't find it in the app store. So when you build from pc to mac you don't change any settings? It should build normally?
You should not need to change any settings, no. It's Unity's job to translate your project into a working program.
I forget exactly how they're installed. Been a hot minute.
I set up this laptop a while ago
the first error seems odd -- the one warning that -macosx_version_min has been renamed to -macos_version_min
I would suggest making a brand-new project and seeing if you can build it
It is possible that this project has some macOS-specific settings that are invalid
Good idea. It will probably build though since it will be created on a Mac not pc but worth a try.
also i looked now through some meta values. I tested with these values on my own setup and my character is totally disabling
The place the project was created should not matter
I have gone back and forth between Mac and PC in both directions several times
By default, there should be no reason for a project you created on one platform to fail to build on another platform
It is possible to add stuff that will fail on some platforms (e.g. if you start depending on native libraries)
Hey guys.. is there a way to place that on update, and make it happen only 1 time? and never happen again?
Make a bool that has to be true for the method to be called, and then disable it in the method
make sense ty
Maybe all your rigidbody masses are set to like 1, and they use way higher masses
I suggest looking up real human bodypart weight proportions and using those as base values, then tweaking from there
yeah i think they used different masses. I already have the right proportions and scales
they used very low masses, maybe 20 times smaller
that's strange
and joints mass scales are 1
And a position spring/maximum force in the tens of thousands? 🤔 Sounds a bit off but idk
🤷♂️
Ragdolls take a ton of tweaking. My advice is to make a ScriptableObject that holds basic settings that you can adjust while playing for easy tweaking+debugging
but the prob is that that need tohappen many times ..
Whenever you need it to happen, set the bool to true
Do you mean that you need it to happen for an extended period of time and then turn off?
For example I used something like this in my older project
It helped me finally get the active ragdolls working decently
that sounds correct
if i walk up it will spawn a big floor square map to the top.. and also for the sides or below
i am trying to create a system for an infinity map but trying to invent one as I just find comples stuff in the internet
and that I dont understand
you mean like minecraft?
what do you mean by infinity map?
huh i think they changed the fixed update time to 100 from 50
check out on google or youtube the game vampire survivors or halls of torment
u can walk infinty to where ever
and the floor is there always
i still don’t understand
😦
you mean the map is a toroid? so it’s one space that repeats if you walk into the edges?
Oh yeah. Ragdolls usually need more physics steps to be stable. I suggest tuning your solver settings up also. Here's what I used
I still get the occasional ragdoll glitch, but that happens in every game lol
Ohhhh I see
So I built a new project in Mac and it built without errors. Granted there was nothing to the scene
i think to make a toroidal space in 2D, you need to define teleporting at the edges
well I dont know how to do it.. i need that who ever the player walks.. Y or X it will have map or spawn a new one so I will always have somewhere to go infinitly
i might even do something dumb, like making 8 copies in the map in the grid around
and make it appear when u reach a part.. well its a way to do it but if I want to walk 2h non stop
and if one of the copies fully enters the main area, teleport all the copies around to stay at the grid
what I’m saying is basically 9x the cost, but it would be simple and work
maybe just 4 copies for up/down/left/right. This way the screen wrapping works right
I wonder if some of the assets I purchased use native libraries . Could that be it?
Yes. Those might be architecture or OS specific
ok will think about something ty
Hi, I have an issue on my game. I tried to change my player to a new GameObject. I added all the component he needed but when I setup this GameObject into my RoomManager to make him spawn, it can move but it flies and I don't know how to affect gravity correctly. I'm using PhotonNetwork idk if it's important but I use it
Thanks. Let me look into that! Appreciate all your help !
Is it flying like upwards or just simply not falling to the ground?
Gravity should be on by default in a rigidbody
And how are you moving the player, show code
It's possible that your ground check is also hitting the player's collider. Make sure you configure its layermask properly
I realized if it does use native libraries wouldn’t it not work in editor too? I get no errors in editor prior to built
Yes it's flying upwards, there is my movement script : https://gdl.space/vinenezasi.cs
And there is the issue in my game : https://streamable.com/2jl8om
I don't see you flying upwards here
Just not falling
First check that your grounded bool is what it should be
Looks like you're setting y velocity to 0 in CalculateMovement
It's because the spawnpoint is already upwards and there is a invisible roof.
But if i spawn on the ground i'm flying to the ceiling
Does the gun have a collider?
Maybe that is triggering your ground check
I'll sent you another video from my last GameObject and it works perfectly
Why not just answer my clarifying questions
Debug.Log or otherwise check that your grounded bool is false when you are in the air
If it is true, then you know that the problem is with the ground check
Sorry but idk how to verify this
Debug.Log("Grounded: " + grounded)
That's how you print a value
Or add [SerializeField] to grounded so it shows in the inspector
private void OnTriggerStay(Collider other)
{
Debug.Log("Grounded: " + grounded);
grounded = true;
}```
Do it in the start of FixedUpdate
okk
It's false
Don't DM me, it's against the rules
People will help you here in this channel if they can
How expensive is the NavMeshAgent.SetDestination function? Assuming i have 100 enemies that follow the player, do i want them to update that once a frame or should I stagger it? Was thinking about not updating it till the player has moved a certain distance
is that only components you have ?
Very similiar looking issue to Julien's issue above. Might be for different reasons tho
Make sure you aren't colliding with your sword's collider
root motion on animator might have somethin to do with it?
Yeah could be
try it with it unchecked?
I would avoid calling it every frame -- but not for performance reasons
I had an issue where an enemy couldn't move at all if there was not a path all the way to the player
It looks like it was taking more than one frame to calculate the path in this situation
but since I kept demanding that it calculate a new path, it never finished...
it work or no?
That might explain why my test AI didnt move when I was far 
Oh good point, thanks
you tried without player movement
find out whats causing it first
not much to go on from wat I see lol
I fix my problem, it was the animator
I removed the Animator and the GameObject stopped flying
try to create a new animator
is there any component i can add to the game object to be able to change its alfa on an animation to make a fade out? Just like canvasGroup for canvas
gameobject doesn't have an alpha
So, is there any way to change alfa to this both parent children sprites?
And if its possible in just one animation...
like what i'm doing with this canavs...
But with a sprite
change the alpha on the sprite renderer color
I would maybe even try GetComponentsInChildren<SpriteRenderer>() or <Image> or whatever
this is an animation, so it's more restrictive
but you won’t be able to do this easily without code, i think
he used a spriterenderer
I'd just make your own CanvasGroup-y component
Make a component that holds a list of sprite renderers
you should be able to add both alphas in one animation i think
It sets their alpha every frame
spriterenderer has a .color set property you can work with to set alpha
Now you can just animate the...SpriteGroup, I guess
I thought that... But ill try to do what fen Said me... Just to try something new
either way, you will want some simple code for this. I do this all the time for debugging, and it takes like 1-2 lines at a time
doing it with code is better
if you change SpriteRenderer’s .color, it will change for the animation too
true
that makes it super simple
in debugging, I normally add a line in debugging to see a bool:
if (TryGetComponent(out SpriteRenderer s)) s.color = myBool ? Color.white : color.red;
toss that in an update loop, and it becomes super easy to see what things have certain bools active
in your case, GetComponentsInChildren<SpriteRenderer>() in Awake()/Start(), then set them as needed
is fixedUpdate an appropriate place to call movement force functions, or it force * time.deltatime superior in some way?
for the most part, rigidbody should be moved in fixedupdate
impulses are fine not in fixedupdate tho
thanks
so many old books and tutorials say update() and time.deltaTime and it seemed odd
you can use time.deltaTime in fixedupdate, it automatically 'translates' it to fixedDeltaTime there.
so I tend to just always use time.deltaTime
What's fixedDeltaTime?
you should not use time.deltaTime on rigidbody at all
https://docs.unity3d.com/ScriptReference/Time-deltaTime.html
"When this is called from inside MonoBehaviour.FixedUpdate, it returns Time.fixedDeltaTime."
time.deltaTime is fixedDeltaTime in fixedupdate
thats not the part I'm talking about.
hence just use time.deltatime everywhere so you don't accidentally start using fixeddeltatime outside of fixedupdate.
https://docs.unity3d.com/ScriptReference/Time-fixedDeltaTime.html
basically 0.02 by default
Still pointless to multiply with fixedDeltaTime. ForceMode.Force (which is default) already uses delta time
that's what I'm saying, just always stick with deltaTime
Im saying you shouldnt use delta time here at all
I'm not saying use it in ForceMode.Force, just generally when you reference a deltaTime somewhere, there's really no need to use fixedDeltaTime anywhere, as anything that involves the fixed delta time should be done in FixedUpdate anyway.
I see your point, it's a style choice
At least, I haven't ever ran into a situation where I needed access to fixedDeltaTime outside FixedUpdate. I have however accidentally used fixedDeltaTime in Update in the past, so why bother with the possibility of making that mistake in the future :p
So, just to clarify, because there is some debate apparently;
Will this work without any wierd framerate based problems on the slow school computers I need to present this project on?
because I know if I put this block in Update it would act wierd without integrating time.DeltaTime
This looks correct
Again, AddForce multiplies the value with fixedDeltaTime by default, so you shouldnt use it with forces
FixedUpdate gets called at a steady rate, so each cycle you would add the same amount of force. So regardless of framerate you should be getting the same force this way.
Thank you
also is your IDE configured or is just the theme like that, your methods should be yellow default ?
This is all default theming, I'm pretty sure
never configured it since it worked for me
do you see suggestions . you don't get intellisense ?
huh thats weird..
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
it is visual studio 2017, if that matters
it's the version I had installed for a c++ course a couple years ago and never needed to change
lol
you should upgrade to 2022
huh yeah that is a few more suggestions
its wayyyy better
what's different?
what's intellicode?
that sounds like corpo speak for ChatGPT integration
nah gpt is garbage in comparison
its just AI that works off your own code, probably a little help from github pilot
The difference is whether it's trained on the entire internet or on specifically your own codebase
Still no replacement for actually knowing what you're doing
but at least if there's any mistakes in it they're your own mistakes in the first place
yup. just makes some things a bit easier to TAB
so I can do stuff like ask questions like "What's the syntax for player input" because I always forget because I need to do it exactly once per project?
nahh its not a prompt tool
okay, that's good
you staart typing certain logic it almost finishes the method for you
well suggests it
its just convenience nothing intrusive
No, it's more like, you type if (Input. and it'll suggest filling out the rest with if (Input.GetAxis("Vertical") > 0) because the line before this was checking horizontal
VS gang
It's important to note: We don't have an irrational hatred of AI coding, it's just that ChatGPT is specifically bad at code because it's meant to be a language model. It speaks, it doesn't code. Purpose-built AI code assistance is perfectly viable
oh, definitely
I occasionally use it, just because sometimes the question is "what's the name of this method" and it's faster than wading through tutorials amd/or bothering someone here, and it's usually right
but I'd never trust it with anything important I couldn't verify in less than two minutes
I just ask it menial tasks like a secretary
never code tho
"Give me a list of 50 names, comma separated"
bam
interesting, what does Rider use for intellicode?
this is copilot
what's the horizontal equivalent of transform.up?
huh?
transform.right?
Hey guys, if I want to get access to something in a child like the ExperienceGet here how do I do it?
_player.child.transform.position? something like that?
You can make a serialized field for the child transform and just use that directly
and if I have a collider in the child.. and I want to do a check for the collider of the child?
What do you mean by doing a check with that collider?
or just use GetComponentInChildren<T>() on the parent if there's only one type of collider as a child.
I think you have to specify the name of the outermost parent for that to work fast
transform is the parent
so if there's a BoxCollider on ExperienceGet just do transform.GetComponentInChildren<BoxCollider>() on the Player transform
ok thank you
(as you can see that gets complicated when there's multiple components of the same type in the children)
Did you mean to reply to someone else lol
that was to everyone that sent a message trying to help me.. including you 😄
Another reason to just use a direct reference [SerializeField] Transform myChild; and assign it in the inspector
What I need is something like.. if something gets into the child colission area, do something.
well, are we speaking of a trigger or a collider? if there's just one collider on the object altogether, just use OnTriggerEnter or OnCollisionEnter
if there's a child component with a collider the collision events gets passed to the parent.
I mean a colider set with IsTrigger on.. So when something enter inside the collider of the child.. something happen
so if your hierarchy looks like
player (no colliders)
- collider (box collider set to trigger)
then you can just use OnTriggerEnter on the player
i have a collider also on the player .. but the collider on the player is for other stuff and the collider in the child will be to attrac or collect EXP but that area of experience collection needs to be way bigger than the player area that is why i created a child to contrl that
is there a channel to request services?
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
if the player has a collider, and the child has a trigger, then that would still work.
I don’t believe that is seen often, is there a more widely seen place to post listings? perhaps Reddit?
if the player has a trigger too, then you can comparetag
or another discord server?
Sorry, i am confused. So, the player has a collider. This collider is to check if an enemy hit the player be it with something or just touching the player. and the child has another collider with a way bigger area that will check if it collides with experience on the floor far from the player to fetch it. So What I need is to say on trigger enter from the child do something and not from the player.
So imagine I want a on trigger enter to do something for the player and one for the child. both with dif logic.. that is what I need but trying to search here still cant find an answer 😛
Use OnTriggerEnter on the parent. Do all the changes from there
You could use two scripts and send info from the child to the parent
that is what Chatgpt told me
Or you mean you need to detect if the parent or the child trigger was hit?
No, it is checking if the incoming collider is a child, that is wrong. You would want to check if the receiving collider is a child, which is not possible
Are you trying to check if this object is colliding with one of its own children?
no
AFAIK theres no way to detect which trigger collider in the receiving object was hit
So you would need a separate object instead of a child
That's why you need to scripts or a way to sub to them individually
I think that they already have a child GO in the player
Are you reading my answers?
Put the second collider on a separate object, not a child
Can you not do
colliderA.OnComponentStay += MethodA;
colliderA.OnComponentStay += MethodB;
Otherwise you have no way of distinguishing between them
That doesnt exist
Does it
@solemn fractal
private void OnCollisionEnter(Collision other)
{
Debug.Log(transform.name + " collided with " + other.transform.name);
}
private void OnTriggerEnter(Collider other)
{
Debug.Log(other.transform.name + " entered trigger of " + transform.name);
}
but if its another object and not a child.. how can I make both have the same position always? I will need to put iton the update method to check that all the time?
Yes, update it manually
Or maybe put them both under an empty parent and move that parent instead 🤔
Both are valid options
hahaha damn, i thought that would be easier.. but well thank you
ok thank you
Why not just have the second collider be on a child game object to the player?
that doesn't trigger OnTriggerEnter on the parent.
Because the OnCollision/OnTrigger event will be sent to the object that has the rigidbody, not the one that has the collider
The player has a rigidbody right?
I don't think a child GO with a collider sends any events to the parent
RB or not
It does though.
Well then
The object with the rb will receive the events, thats it
Why not just have the OnTriggerEnter event be on the XP, then it can very easily use GetComponentInParent to get the player object and call a function on it
Don't put the OnTriggerEnter on the player, put it on the thing you collide with
If the XP hits a trigger that isn't that one, the GetComponentInParent will fail and you can just not do anything with it
I wrote a workaround for that here, but I think @solemn fractal will be good with the setup I showed in my gif.
https://stackoverflow.com/questions/69741488/how-to-know-which-collider-triggered-the-call-to-ontriggerenter-in-unity-on-a-g
ok thank you i will check it out
That's probably best. write an XP script to add it's value to what it collides with
Cool but seems very complex compared to just having it as a separate object
Which is what I did when I needed a proximity trigger collider around my player that has a rigidbody
yeah fair that solution was mostly because i needed a lot of different child colliders which all indicated different parts of a boss
Dont get me wrong - your solution could be handy in some situations
the hierarchy is also a bit better but I would suggest Pedro to just stick with a simpler soluton like putting both a trigger and a collider on the same object
Wont work if the parent has an rb. The rb will receive the collision/trigger events
Though OP didnt clarify if it has a rb but I assume so
