#π»βcode-beginner
1 messages Β· Page 21 of 1
I believe trying to set it on Euler angles can cause other values to change as well.
I had this happen and they certainly don't match the inspector.
Unlike in the inspector where u just see the raw values, the Euler angles I guess let's say readapt the values. If I remember correctly, you won't see 360 degrees in Euler angles for example.
Bad thing, I tried this already and it didn't work.
I tried rotating something on the X axis and whenever it clocks to 180 or 360, y is somehow affect. -_-
screenshot your External Tools in preferences inside unity
show us cuz when you change the default IDE, that IDE opens up when you double-click on the code . . .
How do I get there?
the link i sent you tells you how. did you even look or follow the tutorial at all?
spoiler alert: they did not read
Bits of it
then don't say it didn't work if you "didn't" do it . . .
Yes, let me go back and read it
Me=code beginner
fitting for channel
Ikr π€
Anywayyy
I shall set my stuff up until I Get a pc to actually start coding on π
you can code on a crappy pc . . .
you can still learn to code meanwhile
you can, just not some fancy, shmancy, AAA graphics one . . . . . .
Thatβs what all the hype is all about tho π€βοΈ
not really. you heard of indie games?
a good game != good graphics
ever heard of amongus, flappy bird, candy crush?
what about heartstone ?
Neva heard of it
WHAT
Candy crush was made by one person?
Oh wait
Wrong topic
how you never heard of heartstone
Idk
RimWorld, terraria, Minecraft
ig ur not into card games π
I'm honestly not much of a card game fan. 
OMG I LOVE RIMWOLRD
I love kenshi to π but idk if it was made from Unity
but i suppose thats considered AAA cause its blizzard game, just thought it was neat it was in unity
Aye.
Oh, was the discussion about games made in unity?π
Rimworld isnβt made in Unity?
BRUH
I thought it was about good games != graphics.
Got my hopes up for nothin π
No
I don't think so, no.
Well jokes on you I already have a game that I wanna make
But I has no skills to make t
time to get learnin
Is ultra kill made in unity?
yus
Wot dat
It otay
I shall rant about my game idea
TOMORROW
bye people π
that's for #archived-game-design not here . . .
public class LookAtMouse : MonoBehaviour
{
// Update is called once per frame
void Update()
{
var dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
var angle = Mathf.Atan2(dir.x, dir.y) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
} ```
how do I make the player look at the mouse. right now its looking the opposite way
But today is a Zzzzzz
i thought someone answered this earlier, no?
Meπ
just flip it . . .
ok, sorry didnt see the message i wasnt at my comupter
@cosmic dagger Thank you, I'm absolutely technologically bankrupt. I finally got it working
I have a Combat Script with a reference to my Character Script
While combat is happening and the character kills a monster the Combat Script will send experience to the Chracter Script
But on level up, I need the Character Script to tell the Combat Script to re-calculate damage
How would I go about this?
use an event . . .
that's the Invoke thingie not?
try to keep the character and combat mechanic separate (non-dependent) from each other . . .
so I should re-calc damage before every attack?
but why should the character script inform the combat system to re-calc after a level up?
because the character script has the stats and the stats determine the damage
Yeah, calculating the damage for each attack would be the most reliable way.
doesn't the combat script have the stats of the character for the attack?
You could use a cache and "isDirty" kind of system, but that might be over engineering.
yeah but it only gets it at the start of the script and never updates it
how are your stats stored? i figured it'd be a class or collection of stats which would be a reference type . . .
The stats only change when you level up, right? So damage will be the same until level up? I second an event in that case. It could even be an event in the level property setter
I calc damage in the Start() function on combat script
And never again?
nope
that doesn't seem right . . .
So what does leveling up do?
damage should be calculated on every attack . . .
why not? the damage never changes (unless you level up or equip new items)
What about buffs or items?
what if a specific attack has a buff or debuff?
haven't gotten that far yet π
it's an idle game, so damage really shouldn't change often
when you attack, you should call a method to calculate the damage and send that to the enemy . . .
I think the event makes more sense
It won't cost much at all, and that would be quite reliable.
Then you can just change the stuff your damage function uses to calculate damage from
true
I'll just go with that for now π
C# is not like JavaScript right?
If I do
DamageMonster();```
It will finish the 1st function before executing the second one right?
this will proceed in order yes, although im unsure what the comparison of js is for. any language run these til completion in order
it just calls each line . . .
yeah that
but it often results in the 2nd function getting called before the 1st one has finished
Maybe with async it does. I'm not sure it would do that with normal code.
im super curious where you got this idea from, unless you were unknowingly using async
There is also asynchronous code in C#
because literally nothing will run at the same time
it 100% does lol
javascript is sync by default while c# seems to be async
wrong
Wat
No
you 100% should not be throwing out definitive statements like that
no, c# has async code but it's not by default . . .
I've made games in JS before and ran into the issue
you use async in JS to prevent it from executing the next part of the code before the previous part has finished
It could've been the engine or the framework you were using that were working async by default. The language itself is not async by default.
π€ even i am confused what you are now trying to claim. you used async, but are claiming regular functions will run at the same time
I might have the terms backwards
how did you code a game not knowing this?
You seem to have a profound misunderstanding about what asynchronous code is, how JS works and even the issue you were having (sounds like a race condition from USING asynchronous code incorrectly?)
Not trying to be rude..
not claiming they run at the same time
in my example:
DamageMonster();```
JS will not wait for the 1st function to finish before starting the 2nd function
so if the 1st function calculates the damage but takes too long
the damage will already be done before it is properly calculated
you are still wrong on that
It depends on the definition/implementation of your functions. If they are async, it will indeed work as you describe.
But again, that is explictly telling them to work that way. It does NOT work that way by default.
I have used JS a LOT and yes, it will only work that way with async.
my terminology might be wrong, but my point is valid
what no, its still wrong
JS by default does not wait for that 1st function to complete
No, it is not
go try it
I have spent almost a decade using JavaScript
And i am not a fool π€·ββοΈ
I'm looking at google on my 2nd screen and it supports my claim
and I've made games in Node.js and ran into this exact issue
gif of the funny black man walking into a burning appartment with a pizza
alright pack it up boys, google supports his claim
Just tried it. Not async by default.
Im not trying to be rude, but with the people in here telling you otherwise, and you asking a question in #π»βcode-beginner, do you really feel this confident in your statements?
what you are saying is completely wrong and its taught in the very beginning of comp sci courses. you may have experienced a bug, then incorrectly assumed the cause.
or have been using functions that were async unknowingly
Node js has promises, callbacks and other stuff that runs async. So maybe you're confusing with the framework implementation.
seems legit
Exactly what I was thinking. You ABSOLUTELY can get it to work as they said, and fairly easily, so I assume they just slapped some words in (or copied code) and made it asynchronous, then assumed that was the default.
It objectively is not though, or else a LOT more of my code would have been broken
or people legit just say shit to cause a reaction xD
Im a bit embarrased that i can't seem to figure out the logic im trying to go for here, but what im trying to do is run through a list of gameObjects, and if their names are not "x" or "y", then go ahead and enable them. The issue i'm running into is that when i write this out in an if statement (child.gameObject.name != "x" || child.gameObject.name != "y") i get the issue that even if the gameObject name is x, it still gets enabled because its name is not y, so it passes the boolean.
in other words, i want to enable all objects except the two that are named "x" or "y". Is there a way to do it in 1 if statemnet, or do i have to use a nested if statement?
pretty sure u just use && instead of ||?
Just trying to be helpful, but this site explains it well:
https://www.freecodecamp.org/news/asynchronous-javascript-explained/
"By default, JavaScript is a synchronous, single threaded programming language. This means that instructions can only run one after another, and not in parallel."
Async is cool, and useful. C# can do it too.
Just trying to help.
Edit: also, Unity has "Jobs" which enables highly performant threading, and it is AWESOME. They aren't necessarily multithreaded, but it makes it easy to do
dammit, yeah that makes sense
sync is usually the default. You normally need to explicitly ask for async, because itβs otherwise not clear how you split the work.
yeah that was it, thank you!
what you lack in JavaScript knowledge, you make up for in Boolean logic
nah i'm just teasin'
it's speaks of operations, not the entire language and it says "some" . . .
that page is nonense, they talk about async function but fetchData isn't marked as async
yet says the function is async
//DataFetching logic here is probably in the assumption some kind of async call is going on there to the API
Can you provide the link to this site?
yeah because some behaviour in JS is async by default
maybe it's just API calls & database calls or something
but I've 100% run into this issue in the past, it's been years though
anyway, I'm done with this subject
This is the worst tutorial/explanation page I have seen
why would JS have async await if not for this exact issue?
To make functions asynchronous
some type of gpt probably
it's not by default, it is a set of operations created specifically to run code asynchronously . . .
Can you please provide the link to that page
https://www.sitepoint.com/javascript-async-await/ @summer stump
idk why i replied to you random, sorry
here's a good example I think:
https://stackoverflow.com/questions/75564521/why-is-my-internal-api-call-not-waiting-for-response
but here's the site they were referencing, it seems
ah no they use async
I don't remember this shit, it was years ago
I just know I ran into this issue
#π»βcode-beginner message
still waiting on this link
Carby found it
#π»βcode-beginner message
yeah u were right, I probably used async in my function because I needed to wait for API or database
There I fucking typed js on my phone for this
JavaScript Playground Web App
Its not async
now write that with an API or database call π
or just stop talking about it, I really don't care
It still will mot by async u less I make it
The article is pretty poorly written, imo, but it used fetch in that function
Api and db calls are MADE to be async because of the longer response time
yeah fetch def makes it async
yeah this is what I meant to say in my original point, but I didn't remember the exact context since it was years ago
originally you said games not databases
Guys guys I was saying this all along I just didnβt remember cause it was years ago right
assholes ...
I already did lol
π
guess you missed out on unityscript . . .
oh dont even offend JS like that xD
yep . . .
One of the MULTIPLE scripting languages unity used 
when did they just settle on C#?
what's this chart?
Not sure the timeline. I started at like version 5.
Which, looking at the docs, looks about the time they were changing stuff from JS to C# on the backend?
https://unity.com/releases/editor/whats-new/5.0.0
It says "All built-in image effects were rewritten from JavaScript to C#." 
I started with 3. somethibg
what's wrong with built-in image effect being rewritten into C#?
The amount of js to c# translating from unity answers that I have done
Nothing?
I basically learned js by osmosis
oh, you put a little squiting cat face with the name "at what cost"
Exactly, cause it WAS js lol.
But yeah, probably wrong meme
ah ok\
i thought you were saying that converting the code from JS to C# was too costly or something

in the end it all turns into bytecode 
Hello, I'm using Unity 2022.3.9f1 and imported the Starter Asset Third Person Shooter with cinemachine. I've replaced the model by my own as explained in the video tutorial but my character is stuck in Falling animation despite being on the floor
Anyway to fix that ?
random, but how come unity scripts don't define "System" as a name space?
what does the animator graph look like while your game is running?
i calls in using System.Collections; using System.Collections.Generic; but not plain ol System? grrrrr
did you change just the model? or did you mess with the collision box too?
is this a character controller?
Yes
Oh I'm dumb... I forgot to change the "Ground" layer in the controller script like the documentation said. My bad. It's ok now
ahh yeah that'll do it, lol
Thanks π
Guys I have a problem with my weapon switching
sad to hear . . .
Bummer
Maybe... tell us more?
sorry to hear that, but if you're trying to look for help, perhaps you should go ahead and elaborate what the problem is? What are you trying to do, and what's actually going on instead?
i'd wait until you have everything ready before sending out a cryptic, open-ended message . . .
When you switch weapons while reloading it disables the shooting for that weapon for some reason
maybe system might have some classes that by default conflict with UnityEngine, Random etc.
Well that is most definitely a problem yes.
I can provide you with anything because I literally have no idea the source of this problem
i suppose so, im trying to use TimeSpan, and i was wondering what it meant by it saying it was "not defined"
Perhaps care to share some relevant code
I don't think that video really helps explain the issue. Some code would help though
Specifically the code where you reload and fire
Do you use Visual Studio ? mine already adds the namespace a certain class belongs to and you can scroll through them all
My bet would be that you set a isReloading bool somewhere and when you switch you never reset it because you only reset it from a animation event but that event never fires
seems you disable shooting when switching. do you enable shooting for the active weapon?
i use VSCode
bummer, gotta use that Quick Refactor
Wait... so you want timespan, and when you add using System; is says system is not defined?
naw, it prolly says TimeSpan is not defined . . .
no sorry, i meant that before i added using System; it was saying undefined
Sure. This is my update method
!code
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
"The name 'TimeSpan' does not exist in the current context"
Ah, well yeah. It is in the System namespace
Can't use it without that using statement
private void Update()
{
if (!isReloading)
{
if (Input.GetButtonDown("Fire1") && Time.time >= nextFireTime && currentAmmo > 0)
{
isShooting = true;
Shoot();
currentAmmo--;
nextFireTime = Time.time + 1f / fireRate;
}
if (Input.GetButtonUp("Fire1"))
{
isShooting = false;
}
if (isShooting && Time.time >= nextFireTime && currentAmmo > 0)
{
Shoot();
currentAmmo--;
nextFireTime = Time.time + 1f / fireRate;
}
}
if (Input.GetKeyDown(KeyCode.R) && !isReloading && currentAmmo < magazineCapacity && currentAmmo > 0)
{
animator.Play(reloadAnimationName);
Reload();
}
if (Input.GetKeyDown(KeyCode.R) && currentAmmo == 0 && !isReloading)
{
animator.Play(noAmmoAnimationName);
NoAmmoReload();
}
}
when it says It doesn't exist , you can press w/e shortcut quick refactor in vscode is, it adds namespace, should be the lightbulb icon
show the Reload method . . .
Those are the respective reload coroutines and methods:
private void Reload()
{
StartCoroutine(ReloadCoroutine());
}
private void NoAmmoReload()
{
StartCoroutine(NoAmmoReloadCoroutine());
}
private IEnumerator ReloadCoroutine()
{
isReloading = true;
yield return new WaitForSeconds(AmmoSeconds);
currentAmmo = magazineCapacity;
isReloading = false;
}
private IEnumerator NoAmmoReloadCoroutine()
{
isReloading = true;
yield return new WaitForSeconds(NoAmmoSeconds);
currentAmmo = magazineCapacity;
isReloading = false;
}
and the method to switch weapons . . .
I use a seperate script for weapon switching
ye i know, but now that @rich adder bought up that it could cause come conflicts with UnityEngine, my game feels like, "weird" with it on... idk if it just in my head tho
What conflicts? Like namespace ambiguity? That is easy to solve and not a reason to avoid System
what's the problem? you can just add the namespace, done deal . . .
ah ok
not what i said.. I said its maybe not in the file by default because some classes have same name and its ambiguous
If you disable the entire gameObject that runs the Reload coroutine it will not finish the coroutine and thus isReloading will nver be set to false
oh ok
as @charred spoke mentioned, isReloading is never set back to false when you switch weapons . . .
use an elipses one more time, and i am going to react to your next message with an angry emote
Oh yeah that's definitely the problem:
using UnityEngine;
public class WeaponSwap : MonoBehaviour
{
public GameObject[] objectsToToggle;
private void Update()
{
for (int i = 0; i < objectsToToggle.Length; i++)
{
if (Input.GetKeyDown(KeyCode.Alpha1 + i))
{
ToggleObjects(i);
}
}
}
private void ToggleObjects(int activeIndex)
{
for (int i = 0; i < objectsToToggle.Length; i++)
{
if (i == activeIndex)
{
objectsToToggle[i].SetActive(!objectsToToggle[i].activeSelf);
}
else
{
objectsToToggle[i].SetActive(false);
}
}
}
}
coroutines stop running on a GameObject when it is disabled . . .
bruh, check all my messages, like, ever . . .
Make a CancelReload function that you call before disabling if isReloading is true. Just set isReloading to false, but don't do the ammo
yeah, fix those edge cases . . .
Also I feel like the script is pretty messy
nvm i misunderstood what nava meant
What would you do for weapon-switching?
when you switch weapons, call the cancel method on the active weapon . . .
I saw one like a week ago without one, and it was memorable π
What would CancelReload do?
"Just set isReloading to false, but don't do the ammo"
This?
Yep
Just don't add the additional ammo, and reset the bool
And I can call the function using cs OnDisable
right?
give it a try and let us know . . .
off topic, but why do you end all your message with an elipses?
Brand recognition π
i have a few, depends on the context. questions and directing ppl to proper channels are final remarks that end any open-ended conversation . . .
@summer stump what do you mean exactly by "but don't do the ammo"
was that meant as a reply to me?
or were you replying to Aeth, and your reply just so happen to answer my question as well?
.
nope, i replied to their message . . .
oh, funny, i think you answered my question as well lol
private void CancelReload()
{
isReloading = false;
currentAmmo = currentAmmo;
}
Something like this should cut it, right?
@cosmic dagger

if it answered it, then that's a twofer . . .
CurrentAmmo= currentAmmo does nothing
again, try it out. no one will know until it's tested . . .
so, you use an elipses to show that the conversation is still open ended/continueing? interesting... i guess i do the same thing sometimes

it has more than one meaning. i take the creative writing approach . . .
How come? I want to set the ammo to it's current count rather than to the mag capacity that happens during reloading
if currentAmmo = 5, that's the same as saying:
5 = 5;
```it changes nothing . . .
oh ok, i think i get it
(i do not)
Nevermind then, I guess that's what happens when you prgram in Python for 2 years
You could cache the ammo as something like preReloadAmmo (which may or may not be 0) and in the cancel reload just set currentAmmo to that
And if not, then do a full magazine
Interesting idea
the issue is that ammo's current count is the Mag capacity, so you're just setting it to itself, basically meaning it's being left at the mag capacity
you shouldn't change the ammo count until after the reload is done. if you switch weapons during reload, the current ammo should not change at all . . .
I think that's what my coroutines are already doing ```cs
private IEnumerator ReloadCoroutine()
{
isReloading = true;
yield return new WaitForSeconds(AmmoSeconds);
currentAmmo = magazineCapacity;
isReloading = false;
}
private IEnumerator NoAmmoReloadCoroutine()
{
isReloading = true;
yield return new WaitForSeconds(NoAmmoSeconds);
currentAmmo = magazineCapacity;
isReloading = false;
}
so what's the problem with the ammo?
Should I put the isReloading bool above the ammo set or will that change absolutely nothing?
#βοΈβphysics i asked a question in this channel not sure if itβs better suited for here if so lmk and i will move it
There's no problem with the ammo. When I swap weapons while the reload animation is playing, it disables shooting for my weapon
yeah, that's the original issue. did you test what we said from earlier?
You mean making a CancelReload() function and calling it OnDisable?
Didn't work unfortunately
private void OnDisable()
{
animator.Rebind();
CancelReload();
}
private void CancelReload()
{
isReloading = false;
}
did you check if those methods were called? place logs in cancelReload and OnDisable . . .
What should I log specifically?
anything. you're just testing if the method runs. the log will inform us it does cuz that line of code was executed . . .
just log the method name or smth . . .
private void CancelReload()
{
isReloading = false;
Debug.Log(isReloading);
}
```?
private void OnDisable()
{
animator.Rebind();
CancelReload();
Debug.Log(isReloading);
}
It should logically return false
yeah, but you should name it to know what value you're looking at . . .
Debug.Log($"<color=magenta>CancelReload</color> | isReloading: <color=cyan>{isReloading}</color>");
Debug.Log($"<color=magenta>OnDisable</color> | isReloading: <color=cyan>{isReloading}</color>");
well, it sets it to false . . .
Maybe if I handle the shooting with a seperate method and call it in ```cs
OnEnable
it still won't allow you to shoot when you switch back to the weapon?
when you switch back is isReloading still false?
How do I check that?
log the variable in OnEnable . . .
Maybe I can just make my WeaponSwap script communicate with my Shooting script to disable itself while the animation is still playing?
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
this is the nastiest, overly long line of code i've writen, but by jove it works:
||ScoreBoard.transform.GetChild(1).GetComponent<TextMeshProUGUI>().text = "Time:\t "+((int)TimeSpan.FromSeconds(currLevelStats.time).TotalMinutes).ToString()+":"+TimeSpan.FromSeconds(currLevelStats.time).Seconds.ToString("00");||
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
This is the full code
@cosmic dagger
No
π₯± cs if(ScoreBoard.transform.GetChild(1).TryGetComponent(out TextMeshProUGUI text)) { text.text = $"Time: \t {(int)TimeSpan.FromSeconds(currLevelStats.time).TotalMinutes} : {TimeSpan.FromSeconds(currLevelStats.time).Seconds:00}"; }
Wait wat
Nope, it's too late. You said No, and now it can't be changed.
Stop looking at it!
@cosmic dagger I found the problem
I fixed it
Thank you
It turns out we were looking at the wrong value
We thought there was something wrong with the isReloading bool
In reality our fix worked, but the currentAmmo was simply 0
Hi! Is there a way to declare new variables for each enum? I have an enum of collectibles (coin, files etc.) and want to declare a new integer for each one but want to make it in a way where if I add a new enum it would automatically make a new integer for a counter of how many of those items are collected?
idk if there way to "add" new value to enum in run time, but you can use Enum.getname.length to see how many value in enum
and you may need array, use enum as the index
ty!
Guys
How do I handle grenade throwing when my grenade prefab explodes after a short delay
Which means after said short delay, Instantiating the object doesn't work anymore
Why wouldn't it work anymore? You can instantiate prefabs an infinite amount.
Because the prefab literally destroys itself
No, the prefab sits in your Assets folder, not in your scene.
It will never destroy it self.
Guys, how do I anchor TMP to the bottom left of my screen
no, since format is undefined
u can make ur own ig
How can I make my camera not follow the player when the player falls into the void.
I need it to anchor on all resolutions
if(player not in void){
camera follows player
}
```now camera only follow pleyer if player is not falling into void
hey, could someone tell me how I can make a path along which the Enemies should move, and what I mean here is not specifically about marking lines or points, but the entire path in which the Enemies would move randomly when it comes to their appearance, but they always went towards the end of the path and when Ally appears on their way in a certain area, they cancel their further progress on this path, they will just start attacking him, I'm asking because I don't really know how to go about it, I've heard something about navmesh but I don't know if it's a good solution and I'm not entirely sure how it's supposed to work.
Show us the camera script
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public float FollowSpeed = 2f;
public float yOffset = 1f;
public Transform target;
// Update is called once per frame
void Update()
{
Vector3 newPos = new Vector3(target.position.x, target.position.y + yOffset, -10f);
transform.position = Vector3.Slerp(transform.position, newPos, FollowSpeed * Time.deltaTime);
}
}`
You can add a variable to stop following the target after he reaches a specific y level
yeah thats what I am trying to do right now
It's easy
add this variable
public float stopFollowingYLevel = 10f;
and then the camera logic under this condition:
if (target.position.y <= stopFollowingYLevel)
{
Vector3 newPos = new Vector3(target.position.x, target.position.y + yOffset, -10f);
transform.position = Vector3.Slerp(transform.position, newPos, FollowSpeed * Time.deltaTime);
}
another trick is you can add colliders under your map to define where the void starts
and if the camera triggers the colliders it stops following the player
Doing it based on colliders is probably better. you can define areas where this happens so you arent limiting yourself to design around the Y value. Also itll allow you to have more complex level design.
You could have some event on the player, that the camera subscribes to, which happens when the player enters the kill area. Then another event for when it respawns to tell the camera to start following again
could someone help me please
I have created a simple ScriptableObject. After doing some changes to the script, the .asset file no longer loads properly. How can I fix that?
Here's what it looks like:
Here's what it should look like;
You changed the name of the file.
Did you also change the name of the class?
Do you have any compile errors?
I want to know why unity does not included the Abs method of System.Numerics.Vector3 in UnityEngine.Vector3?
https://learn.microsoft.com/dotnet/api/system.numerics.vector3.abs?view=net-7.0
I'm trying to get my camera to rotate vertically without it becoming lopsided like in the picture. Any ideas?
public static float rotationX = 0;
public static Vector2 rotationLimits = new Vector2(80, -80); // Vertical rotation limits
private static Vector3 offset = new Vector3(0f,0f,0f);
void RotateCamera4(float x, float y)
{
Transform target = Object.PlayersMainObject[0].GameObject.transform;
// Get the mouse input
float mouseX = x * 2f;
float mouseY = y * 2f;
// Rotate the target horizontally
Camera.main.transform.Rotate(Vector3.up * mouseX);
// Rotate the camera vertically
rotationX -= mouseY;
rotationX = Mathf.Clamp(rotationX, rotationLimits.y, rotationLimits.x);
// Camera.main.transform.Rotate(Vector3.left * mouseY);
// Calculate the rotation quaternion
Quaternion rotation = Quaternion.Euler(rotationX, target.eulerAngles.y, 0);
// Calculate the new position of the camera based on the rotation and offset
Vector3 newPosition = target.position + rotation * offset;
// Apply the new position to the camera
Camera.main.transform.position = newPosition;
// Make the camera look at the target
Camera.main.transform.LookAt(target);
}```
I want a scene wide tick speed I can call functions in, my best idea is to make a coroutine call an event every x amount of milliseconds and to then subscribe to this event from other scripts. does anyone have a better idea on how to implement tick speed?
Use this pattern https://blog.unity.com/engine-platform/10000-update-calls but call the MyUpdate when a timer hits your desired seconds
thanks
Does anyone know how this is supposed to work? Not sure why this grounded check isn't working..
I think thatβs a movement code
For such things as crouching
I know, I wrote it :)
What im saying, I don't know why the IsGrounded check isn't working
Just DrawRay the Raycast you made. My guess its probably too short because you shoot it from the middle of your controller.
ahh right
I was unaware it comes from the middle
That works perfectly, Just increased the value
My next question is how would I get this to apply the force on the local axis?
Instead of Vector3.forward, use transform.forward.
Vector3.forward is the forward in world space. transform.forward is the forward in local space of the transform.

Is there a way in unity to pass a component of an object to another? I'm trying to assign an object that has collider on it and I want that object to be assigned inside one of the objects inside a prefab. So what I did is I created for each, one for a scene and one inside a prefab, I created a script to instantiate the one in a scene.
How to clear previous debug.drawray ?
So I have a coroutine that I am using try and make my game wait a frame before continuing to do check. The way I had it explain to me was that in the coroutine i needed to have everything that needed to happen before the wait above the yield return null; and then the game would wait a frame and then run everything after it. After looking at it through a debugger the code runs properly up until the yield statement which instead of pausing for a frame its exiting the coroutine instead of waiting. Does anyone have any idea what I am doing wrong? https://paste.ofcode.org/35D8a7gYttesrfHThbiHFcx
Give it a time.
https://docs.unity3d.com/ScriptReference/Debug.DrawRay.html
but I want to see only the ones drawed this frame
Well, duration by default is 0 
So it should clear it if you don't put anything higher then 0.
mmm, ok
Can you perhaps show the code?
I see it. I just wanna be sure that the green line wasn't drawed before.
Yeah, then it's fine. By default it clears every frame.
Sure, you can pass any component to another gameObject if you have a reference to the other script component.
You could also search for it. You could also make a gameManager that has all these references so you don't spend time searching. There are a bunch of options, don't know which one is best for you.
This is a large method. You may want to specify where in the code you have the problem. Does it not continue the coroutine after any of the yield statements? Log the current frame before and after the yield. Also, you have if statements, do they evaluate to false to continue execution?
from how it was explained to me the whole thing should have be a coroutine. The problems is on lines 28 and 51. There is no if statements that would continue execution as this is simple something that gets called to create things and shouldnt return anything. The code after the yield does execute on the next frame, but the problem is that the coroutine is called multiple times in the first frame and then all of them execute the code after the yield on the next one. What I am trying to achieve is having the game stop everything its doing once it hits the yield update the frame and then continue execution because the subsequent runs of the coroutine rely on information generated by the preivous run of it.
Why it doesn't change the parametr in Animator?
Debug.Log($"Index to set: {indexAnimator}, attack direction: {attackDirection}");
fallAnimator.SetFloat("Fall", indexAnimator);
Animator is referenced, this is the only place in code where im changing this float
i guess the best way to put this is that the routine is running 5 times and completing in 2 frames when what I need is for it to run 1 time for 2 frames and then run again doing that sequence 5 times
Worth pointing out I do have the execution in a for statement
is there a way to have unity editor load a specific scene when you hit play? I want to work on my scene, but hitting load runs the 'start' scene instead (to get to my scene fully setup)
hey gys newbie here can i ask some help on my code ?
Yeah, that's exactly the point of this channel
just throw your question
Well, you either run the correct scene, or load your correct scene with a script. Not sure what the problem is.
!code
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
and that stack overflow thing
the question is how to do the latter, then
And show the stack overflow error message.
It should be a pretty simple editor script. It would enter play mode and then immediately load a scene.
yes, but making that happen isn't exactly obvious -- putting an object in the scene that does it would throw you back to the start screen every time you tried to play the game
I think you could add a menu item that starts the game and loads the Start scene
the line "neighbourTileScript = neighbours[i].GetComponent<scr_TileBehaviour>();" have been pointed out as the problem by unity in the stack overflow message, but sometimes it just crashes
this dude put the script on binsite and didnt send the link but screenshot.. lel
next time post your code in the website in !code
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
not cool man, im newbie here
your code may create cycle then stackoverflow
editor script, as in code we write to add editor menus that do that?
it was just a little funny to see
since people usually just screenshot their code editor
or is that just how your code editor looks?
it looks like a paste site
yeah looks like gdl
suppose you have two neigbhor tile and they are connected then when you call AltHUD on one of them it calls the other one AltHUD and call back to one, causes cycle
thats why i used the bools oh i think i get it
If the code does execute the next frame, then it's not exiting
If the other coroutines rely on a previous coroutine, then you need to ensure the first one runs until completion
If you want the game to stop everything, you may need to invoke an event that halts execution for the objects you want to stop . . .
your guard doesnt block second call on the same instance i think
if(called){
return;
}
called=true
for all neighbors=>call AltHUD
called=false;
why "called = false;" at the end ?
i was gonna make a list of all neighborsthat are already called
just standard DFS, the called=false actually cant be inside the AItHUD method
The idea would be to mark the tile as being visited already
You clear that mark at the end so that the next search can work.
ok update
U made me understand the fact that in a loop it dont read the rest of the code ofc
now i dont have the overflow
(still dont work lol) Thanks tho
static Stack<instance> path
bool called=false;
public void Method(){
if(called){
return;
}
called=true;
path.push(this);
call neighbors Method()
}
void CallMethod(){
Method();
foreach instance in path, reset called;
}
Hey guys I have this bit of code:
CurrentDay = System.DateTime.UtcNow.ToLocalTime().ToString("dd");
I need the script to just give me the current day, but the issue is that it gets it as a string while I need it as an Int. How can I change this?
int.Parse
Do you guys have the problem where if you instantiate an object through code and immediately under that code tried to affect the instantiated object's components, that code will not read?
I did encounter this problem and I fixed it by invoking the component affecting method 0.2f second later. I was just wondering if there was a better fix.
You probably have some code in Start that hasn't run yet.
When you Instantiate an object, Awake and OnEnable both run immediately (before Instantiate returns)
I did all my instantiations on start
Moving that code into Awake would fix the issue.
The rule of thumb is to set yourself up in Awake, and to then talk to other objects in Start (since they will also have had a chance to set themselves up)
Alternatively, if you need to do some configuration first, the best option is to write your own "init" method
static Stack<instance> path
bool called=false;
public void Method(){
if(called){
return;
}
called=true;
path.push(this);
call neighbors Method()
}
void CallMethod(){
Method();
foreach instance in path, reset called;
}
and to call that immediately
This isn't really helpful, where should I put it?
did you read the docs for it?
no need to round-trip that through a string
What if I wanted to instantiate objects as child of certain objects that are also going to be instantiated in Awake?
if you did have to use the string, int.Parse would take it and return an integer
Sounds fine. Awake will run immediately when you instantiate the object.
You can then access anything that was created in Awake
made me some time to understand, ill try it thx
Why isnt the material being changed? https://i.imgur.com/q6Rotuz.png
ah, this is an easy mistake
materials is a property that returns a new array containing all of the renderer's materials
call CallMethod to start the dfs on each instance, after all instances AItHUD are called then it return from Method, and reset all instance
Save the array in a variable, update the array, and assign it back to the materials property
use the code Fen sent you..
If you were to ever need parse it really is as simple as int myInt = int.Parse(CurrentDay);
although imo using TryParse would be more secure than Parse
That will set all of the renderer's materials.
yayy, what means DFS ? loop ?
Depth-First Search
Oh, ok thanks
in a DFS, you immediately recurse on one of your children
so it goes all the way down first, before trying the next child
you guys are the best
compare this to a Breadth-First Search (BFS), where you check all of your children, then all of their children, and so on and so forth
Okay thanks
I always find BFS more annoying to implement
you can find some animation on youtube of DFS, better to understand
DFS is dead simple. Check if your current tile is what you want. If not, check each child in sequence
note that renderer.materials[1].someField = 123 would work fine -- it doesn't return a new array of new material instances every time. It just returns a new array holding the renderer's materials
Depth First Search (DFS) algorithm explanation
Source code:
https://github.com/williamfiset/algorithms#graph-theory
Video Slides:
https://github.com/williamfiset/Algorithms/tree/master/slides/graphtheory
0:00 Depth first search as an algorithm template
1:04 Simple DFS example
3:30 Depth first search pseudocode
5:10 Finding connected component...
It does make a copy of the materials the first time you access it, though (and then assign those to the renderer)
so that you aren't editing the shared materials
Do i do meshrender or renderer?
either would work here
okay
all Renderers have materials
Being specific might make your code more clear
I got footgunned by this once. I was doing GetComponentInChildren<Renderer> to grab a mesh renderer
Then I added a visual effect, and my code (only after a restart!!) started grabbing its renderer instead
that took a while to diagnose. it was breaking the visual effect.
tysm
What am i doing wrong? https://i.imgur.com/zAqH3FF.png
@swift crag
You're checking if the second material is set to the right material, before assigning the same material, which doesn't make sense. That means that it will never assign OnMaterial unless OnMaterial is already assigned.
OHHHHHHHHHHHHHHHH thanks, thats what i was trying to do instead.
It works now
Why is this not working? The first picture's log is working, but then the Action does not invoke.
Presumably you aren't subscribing to OnNewOfferCreated.
Perhaps you're doing it too late.
Show where you subscribe the one on the right
I dunno, try putting that in awake?
Nah wait, do you serialize the reference to emptyPanel? Or capture at runtime?
verify that this is actually running, and that it's referencing the correct emptyPanel
emptyPanel is a prefab which is instantiated
prove that it's the right panel by including this as the second argument to Debug.Log so that you can click the log entry and see where this is
do this in CreateNewOffer (first image), in Start (last image), and wherefver it is you instantiate the panel
Works exactly right
Hello good day!
I have a problem with intellisence of vs code can anyone help me?
!vscode
I use this but its still not working.
follow every step to the letter.
My GPU usage is consistently at over 90% for an empty scene. I've tried lowering the target frame rate but have noticed no difference. Tips?
show me a screenshot of your package manager window so I can see if it's configured correctly
along with your External Tools settings
@swift crag it is about listening to the event I guess. Because in start, I'm listening to a prefab's event
so you put Application.targetFrameRate = 60; somewhere?
ah, well, that'll stop it from working.
listen to the instance's event
What does the AABB a error mean?
Axis-Aligned Bounding Box.
It means something is positioned at infinity
this can be tricky to nail down.
Sure I'll send you as soon my pc come up thank you.
Yes. And then 30. And then 5
Give whoever's listening to the event a reference to the specific panel instance you need
And did your framerate actaully go down?
click the "Stats" button in the game view
top right corner
But I have 4
Yeah it did, looking at the profiler now
well, surely you want to listen to a specific panel
not just a completely random one
Or is this code supposed to listen to all of the panels?
Oh, that's useful. Thanks
If so, you need to tell it about each panel.
I use this to teleport the Player to a random spawn. I call the coroutine from the start method of my GameManager. However, the player only gets teleported when I start playmode directly from the scene, whenever I enter the scene from my Menu Scene it doesnt teleport the player at all, only the monster. What am I doing wrong?
well, does the GameManager get created in the menu scene?
Well what do you mean?
They have the same script
No, only in the game scene
if you want to be able to listen to the events of ten panels, you need to given references to all ten panels
perhaps whoever spawns the panels can call a method on whatever this is
can anyone help me how to get a component of an object and pass it to another object?
i can't assign the object with component directly in the inspector since I will be assigning inside a prefab
Same script, different INSTANCES of that script
Think of the script as the CONCEPT of a banana, and each of the objects as actual bananas
using UnityEngine;
public class PassCollider : MonoBehaviour
{
public GameObject objectB;
[SerializeField] public PolygonCollider2D polygonCollider;
public static PassCollider Instance { get; private set; }
private void Awake()
{
Instance = this;
CopyColliderToOtherObject();
}
// Call this function when you want to copy the PolygonCollider2D.
public void CopyColliderToOtherObject()
{
// Get the PolygonCollider2D component from Object A
polygonCollider = GetComponent<PolygonCollider2D>();
// Pass the PolygonCollider2D points to Object B
GetBoundObject objectBScript = objectB.GetComponent<GetBoundObject>();
if (objectBScript != null)
{
objectBScript.polygonColliderB = polygonCollider;
}
}
}```
using UnityEngine;
public class GetBoundObject : MonoBehaviour
{
[SerializeField] public PolygonCollider2D polygonColliderB;
private void Update()
{
CopyPolygonCollider();
}
// Function to copy the PolygonCollider2D points.
public void CopyPolygonCollider()
{
var sd = PassCollider.Instance;
polygonColliderB = sd.polygonCollider;
}
}```
I have to wonder what happens if you instantiate something with an event
is there something wrong my script?
Does the event's delegate get copied too?
i need help
i donβt understand what you are trying to do
you want gameobject B to get a component on gameobject A?
yes that's right
you can call gameObjectA.GetComponent<>()
If objectB solely exists to get a GetBoundObject from, just make the variable of type GetBoundObject then you don't need to use GetComponent or do a null check. Also I don't know why you're bothering to set this when you're overwriting polygonColliderB every frame in the other object
you can normally write GetComponent because you are in a monobehaviour class, so the program automatically checks GetComponent in your gameobject
GetComponent normally actually calls gameObject.GetComponent
but you can call GetComponent on any specific gameobject from any other gameobject
idk if that is what is tripping you up
well, it calls this.GetComponent (which is equivalent to gameObject.GetComponent)
I tried putting it in the update method, and while the enemy gets teleported around like crazy the player stays unaffected and can move freely. Any help?
Does the player have a CharacterController on it
Yes
Log the object your'e finding here. I wonder if you have multiple things tagged Player somehow.
I already did that, there is only 1 Player Object
I'm curious about the behavior differing depending on whether you directly started the scene
I guess that could affect update order.
Those things don't like to be teleported. They'll ignore movement that comes from other sources. You can add a Physics.SyncTransforms() after teleporting a CharacterController and it'll override their position with the new one from the transform
Which could make the order between this component and the CharacterController unpredictable
That might be it
CharacterControllers keep their own internal state, including position, and modify that internal vector, then set the object's transform's position to that every frame. It only reads from the transform when it starts. SyncTransforms tells everything "Hey, read from those transforms again, something's changed" and it updates its internal position
Oh that's it! I think I fixed it by disabling the CC before teleporting and enabling it afterwards again
using UnityEngine;
public class PassCollider : MonoBehaviour
{
public GameObject objectB;
[SerializeField] public PolygonCollider2D polygonCollider;
public static PassCollider Instance { get; private set; }
private void Awake()
{
Instance = this;
polygonCollider = GetComponent<PolygonCollider2D>();
}
}```
```cs
using UnityEngine;
public class GetBoundObject : MonoBehaviour
{
[SerializeField] public PolygonCollider2D polygonColliderB;
private void Update()
{
CopyPolygonCollider();
}
// Function to copy the PolygonCollider2D points.
public void CopyPolygonCollider()
{
var passCollider = PassCollider.Instance;
polygonColliderB = passCollider.polygonCollider.GetComponent<PolygonCollider2D>();
}
}```
is this okay now?
Use SyncTransforms instead, it's much lighter weight
But I still wonder why it worked sometimes before
is there an advantage on using the EnhancedTouch class instead of using InputActions for joystick movement?
polygonCollideris already a PolygonCollider2D, you don't need to get the component from itself.- If this is the use case why do you even have a field for
polygonColliderBat all? Just usePassCollider.instance.polygonCollider
Yeah, that was almost it
If you have a script that calls Move every frame, the teleporation works if and only if you teleport after that script
using UnityEngine;
public class GetBoundObject : MonoBehaviour
{
[SerializeField] public PolygonCollider2D polygonColliderB;
private void Update()
{
CopyPolygonCollider();
}
// Function to copy the PolygonCollider2D points.
public void CopyPolygonCollider()
{
var passCollider = PassCollider.Instance;
polygonColliderB = passCollider.polygonCollider;
}
}```
```cs
using UnityEngine;
public class PassCollider : MonoBehaviour
{
public GameObject objectB;
[SerializeField] public PolygonCollider2D polygonCollider;
public static PassCollider Instance { get; private set; }
private void Awake()
{
Instance = this;
}
}
is this okay now?
polygonColliderB is still pointless
If you're gonna use the polygon from the singleton why bother copying it to a variable every frame
just use the singleton
Also objectB literally does nothing
I want to assign the PassCollider object into Cameramachine Confiner2D but that's inside a prefab object
Then do that
you just want one gameobject to query another gameobjectβs components?
I can't directly assign it since my camera is inside a prefab
So use the singleton you made
that's presumably why you made it a singleton
so you can use it
Just set the variable in the camera to the polygon collider in the singleton
You don't need to copy it to a variable every frame
how do I do that?
What I normally do is I have EntityDataHolder : Monobehaviour which stores core information for a given gameobject, including its collider and SOs with specific flags about its behaviour.
Then I have EntityAttachmentHandler : Monobehaviour. This monobehaviour goes onto an object that is attached that keeps as a field a reference to the gameobject to which it is attached.
but do what you actually want with it instead of storing it in a variable
Just delete polygonColliderB and use PassCollider.Instance.polygonCollider when you need to use it
Im sorry for asking much, Im new to unity so I dont have much knowledge
ohh let me do that
using UnityEngine;
public class PassCollider : MonoBehaviour
{
public GameObject objectA;
[SerializeField] public PolygonCollider2D polygonCollider;
public static PassCollider Instance { get; private set; }
private void Awake()
{
Instance = this;
}
}```
```cs
using UnityEngine;
public class GetBoundObject : MonoBehaviour
{
[SerializeField] public PolygonCollider2D polygonColliderB;
private void Update()
{
var passCollider = PassCollider.Instance;
if (passCollider != null)
{
if (polygonColliderB != null)
{
Destroy(polygonColliderB);
}
polygonColliderB = passCollider.polygonCollider;
}
}
}
is this it?
it destroys the component of objectB but it doesn't use objectA's component
What
Literally just get rid of polygonColliderB
that variable does not need to exist
It's completely pointless
it will destroy the instance polygoncollider....
btw why you do it on update, or i miss some chats
Because they have no idea what any of this code means and they're coding by successive approximation
polygonColliderB does not need to exist
Just remove the variable and all uses and references to it
and use the polygonCollider from PassCollider instead
and why is it a polygoncollider2D, and not a collider2D?
That's the least of the problems with this setup
yeah, I think his class should be very simple
using UnityEngine;
public class PassCollider : MonoBehaviour
{
public GameObject objectB;
[SerializeField] public PolygonCollider2D polygonCollider;
public static PassCollider Instance { get; private set; }
private void Awake()
{
Instance = this;
}
}```
```cs
using Unity.VisualScripting;
using UnityEngine;
public class GetBoundObject : MonoBehaviour
{
private void Awake()
{
PassCollider.Instance.polygonCollider.GetComponent<PolygonCollider2D>();
}
}
is this it?
wait, is the whole goal here to get a collider into a singleton?
Why are you getting a polygon collider from a polygon collider
And why are you getting a polygon collider and doing nothing with it
and why does this class even exist
all of these questions
I just want to pass the component of an object to another object
this whole class would just be holding one collider, right? and give you global access to that one collider?
this is not the way to do this
will you help me?
GetBoundObject seems to be completely pointless. You have the collider from PassCollider. It's accessible everywhere. That's why you made it a singleton
Just use that
you are trying to make a singleton, which is a class of which there is only one instance
so you can only hold ONE collider, because there is only ONE instance of the singleton
but why do you even want that one collider to be accessible from everywhere?
I meant I want to assign that object that has PassCollider script attached on it into an inspector of one object inside a prefab
i think we need to back up several steps
there are several layers of doing things wrong that we need to unpack here
Im so creating two object, one from the scene and one inside a prefab
I sent them the link on references, they didn't read it
bro
you need to know how references work
thatβs like, programming 101
this is like trying to learn how to read without knowing the symbols used in the language
alright, i will figure it out myself
you mean you will read the link that tells you how it works?
I've been spending almost an hour telling you what to do, you're just... not doing it
one of these days, the next time someone doesnβt read a link that clearly answers their question, Iβm just going to start copy pasting the text in that link bit by bit into discord
Hi guys,i need to build a game on standalone and i need to see the errors in the console log,how can i print them inside the game?
Make a debug UI where you print the text to
You can enable or disable that ui
yes but how can i access to the console messages?
Cause it is what i am trying to do
You can subscribe to this method:
https://docs.unity3d.com/ScriptReference/Application-logMessageReceived.html
It's called whenever anything goes to the log. You can add in a function that takes the string and prints it out on the UI somewhere
Thanks
https://hatebin.com/pnscqbdeof
The script is to change the glow when pointer enters. It all works fine till I press play and start the game. Then When I come back to main menu. Even though im not hovering over the last pushed button which is play. It still is glowing until I hover over and trigger pointer exit again. Anyone know why?
I'm assuming the object is disabled some way rather than destroyed when you press play
Disabled objects stop all coroutines, so it doesn't finish its fade thing. You should probably have an OnDisable that instantly resets the glow back to normal with no timer
Hmm all right thanks.
Ahh I also need OnEnable too?
Can I just stuff them into my current script? Or could it be cleaner
Ahh I got it work. Thanks digiholic
so unreal has this variant manager.. its cool for things like day / night presets.. (as i build materials i like to switch around)
my question is how would be the best way to go about replicating something like this? (not including the drag and drop preset stuff)
i think i would use Scriptable Objects, and a class with a slot.. then i can loop thru the components and set them according to what SO i have assigned..
i could just use an editor function to swap in edit mode..
i'll give that a shot first and see how it works out
Hello! I was wondering if anyone could point me to good resources about how to use the unity profiler (or some other thing!) in order to identify memory leaks / garbage collection issues and then pinpoint their location in my codebase?
medium always has good articles to get u started.. / familiarize urself with
TYTY!
- look for spike
- click the spike
- expand the call logs
- find the class / loop taking the most time to run
Hey everyone, I am expiriencing a pretty weird issue where my collision doesn't work at all, basically I don't know what mistake exactly I'm making, or if I'm even being crazy, but if 2 objects who just have their own colliders get in contact they should collide somehow, even just crashing if one runs into the other, and mine just kinda ignore each other. Now the thing is that they the obstacle can kill my player on touch with it because of the script i used, but they never collide if i take out the script, so it's kinda as if collider is there but he doesn't work at all. I will gladly provide screenshots or videos if needed, if anyone is willing to help π
screenshot the inspectors of both objects
You have isTrigger selected
So it won't collide
The reason is because I thought it might fix it but it didn't
Triggers simply don't collide. But you're saying it was an issue with it NOT selected?
Yes
Both must have it deselected.
But then how will it react to my OnEnterTrigger2D() btw?
Ok, so, what layer is the player on, and have you touched the collision matrix?
Does any of those have a rigidbody?
It wont. You can use OnCollisionEnter. Or do a separate trigger in ADDITION to a non-trigger collider
Yes, player has dynamic
OnEnterTrigger2D ??
Oh yeah, that isn't what it's called btw. Just the enter and trigger part reversed
I apologize OnTriggerEnter2D*
Ok I'll be frank with you, I did do another project in the exact same way yesterday but I had to redo it because of some setup issues and it did work back then with this same code and trigger being enabled so now I was completely shocked
To see it
And I am also kinda shocked to realise am supposed to just not do it? Even tho it worked yesterday?
Idk I feel like there is a bigger issue to it, or just something i am missing out
Something else caused it to collide. Triggers do not
You had a different setup if it worked
public class Shoot : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
public float bulletForce = 20f;
public float timeBetweenShots = 1f;
// Add Max ammo, reload, mag size
// Update is called once per frame
void Update()
{
if (Input.GetButton("Fire1"))
{
Shooting();
}
}
public void Shooting()
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(firePoint.up * bulletForce * timeBetweenShots, ForceMode2D.Impulse);
}
}``` can someone help me make multiple bullets spawn in each other
https://docs.unity3d.com/Manual/CollidersOverview.html
"A collider configured as a Trigger (using the Is Trigger property) does not behave as a solid object and will simply allow other colliders to pass through. "
Like I said though, just use two colliders. One non-trigger to collide.
One a trigger that is slightly bigger if you want to get that OnTriggerEnter
Or just use OnCollisionEnter
Can you explain "one a trigger that is slightly bigger"
A second collider component attached to the object that has a larger size (if circle, use radius, for example)
That is common for doing a "sight range"
You could do a coroutine and wait between each shot.
Or a timer in update
I assume you meant "can someone help me make multiple bullets NOT spawn in each other"? Because they seem to be spawning in each other already
oops my bad
if anyone has knowledge about using color in scrpits, help would be apprichiated. heres my code:
foreach (SpriteRenderer pumpkin in pumpkinSprites)
{
pumpkin.color = Color.HSVToRGB(0f, 0f, 10f);
}
and here is what it actually does (the V value previously being 100f):
No matter what value i enter for V in the script, it always just makes it 75 and i have no idea why
hsv values only go from 0-1
ah, that makes sense, thank you
This is probably a stupid question so apologies in advance but within my scripts I have a Dialog Manager and an NPC Controller doing what they say on the tin. Now my Dialog Manager is just a singleton with different methods to call different types of dialog however I want to add Character Sprites and names to my dialog window and Im not sure whether to do this in my NPC Controller (the option im leaning towards) and then doing so independent of the Dialog System or somehow try and get a reference in the Dialog Manager to what called the dialog and if its an NPC to set an image sprite and a name sprite
dont you have a custom object for this?
Unsure what you mean by custom object
object , like a class
I'd probably just allow an optional Character speaker parameter in the dialog functions in the dialog manager
I do not, so far Ive just been trying to figure out the best way to do it
the type of which is your ScriptableObject for a character or whatever
the character object should have:
- name
- speech color?
- maybe a font?
- portrait sprite
- whatever else you want
yea SO for each character would be perfect
Is it a problem if my characters are not based on scriptable objects
You will want to have some kind of class that describes a character
it doesn't have to be a ScriptableObject
though they are pretty convenient for this.
I can definitely see how it could be
See this is why I thought it a stupid question because I have a character class that right now just handles movement and things like a LookTowards function, My NPC Controller that I mentioned opens dialog on Interact and I just dont really know where best to put all this stuff
that character class sounds like something completely different
I'm thinking of something more like an object that holds all of the necessary info to describe one of your story characters.
I would not combine those
If you don't have such a thing already, I recommend creating it.
how do I get an int of a float without rouding the values
just using the first digits before decimal
Yeah I would probably say I dont have one right now im not really sure what I would store inside it other than a name and sprite
just cast it
int myInt = (int)myFloat;```
so does that not round it
like
15.6 = 15
it is okay to add more to it later. Characters will need more info than just a name and sprite. Youβll probably add flags to them later, like IsPlayableCharacter, or IsNPC or whatever
When you convert a double or float value to an integral type, this value is rounded towards zero to the nearest integral value. If the resulting integral value is outside the range of the destination type, the result depends on the overflow-checking context. In a checked context, an OverflowException is thrown, while in an unchecked context, the result is an unspecified value of the destination type.
I already do this via seperate controller calsses i.e. I have PlayerController and NPCController Im thinking based on what Praetor said im best off doing this in my Character class.
Ive just managed to confuse myself with the scope of everything, I never thought id have so much going on it would be hard to keep track of π
Would it be a better idea to create SO's and reference them in my class over just creating fields in my class and setting them in the inspector?
im trying to implement a 3rd person camera into my game without the use of cinemachine and have it almost done, I just can't figure out why the camera isn't clamping.
{
float horizontal = Input.GetAxis("Mouse X") * rotateSpeed;
float vertical = Input.GetAxis("Mouse Y") * rotateSpeed;
horizontal = Mathf.Clamp(horizontal, -90, 90);
lookAt.transform.Rotate(vertical, horizontal, 0);
float desiredAngleY = lookAt.transform.eulerAngles.y;
float desiredAngleX = lookAt.transform.eulerAngles.x;
Quaternion rotation = Quaternion.Euler(-desiredAngleX, desiredAngleY, 0);
transform.position = lookAt.transform.position - (rotation * offset);
transform.LookAt(lookAt.transform);
}```

heey, does someone know why the print works but the var doesnt get false? ```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PipesCollision : MonoBehaviour
{
public bool hasCollisioned;
private void Start()
{
hasCollisioned = false;
}
//Check collision with player
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Player")
{
hasCollisioned = true;
print("Te has chocado");
}
}
}```
each character can have a field just for dialogue object / info SO
ideally you don't want this mixed with your Locomotion script etc.
!CODE
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
your clamping input instead of angles ?
bit strange
you set to false at the start of the GameObject and set it to true in the trigger (which you said runs) . . .
would that not work?
Yeah I saw Praetor said the same now im thinking that that I will just put it in my NPC Controller, I have the Player identifying information in my Player Controller so I feel like that makes sense
also i did try clamping the desiredAngleX but that didn't work
what if its Non-NPC player that needs dialogue ?
Im not sure what you mean by Non-NPC player
what?
you said the variable doesn't get false but you set it to true . . .
sorry, i meant why it doesnt get true on the trigger
after the console prints, show is the variable from the inspector . . .
ohh thought you said only NPC Controller have the identifying info for dialogue
it should tbh be something different like public class CharacterInfo or something
Do you set it false anywhere else? Could some code be immediately setting it back?
(In another script I mean)
Thats my bad Im just thinking in terms of NPC's right now and the info like names in the other scripts are not currently used for what im trying to do
could we talk on dm? or i tell it you right here
If that print happens then hasCollisioned is true
How do you know it's not
No sorry. I just pop in and out. If the conversation is here, others will be able to help if I leave or if they know more
So a new class rather than just fields and properties to expose them? How come?
to encapusulate the info
and keep it separate from other logic/code
you don't want a monolith class full of fields
eg mixing movement / stats with other datainfo meant mainly for visuals
cause the var is public and it doesnt get checked the box in the inspector
Then you are looking at a different PipesCollision than the one that logged
Ah ok got you I will do that then, they'll be in the same prefab anyway so easy referencing, Thankyou for your help!
Or something else is changing the variable after it's set to true
let me check it in one moment
oh, i know what happens, but i dont know how to fixe it...
it gets true on the object
not in the prefab
Why would you want it to change in the prefab?
Prefabs are files. They are not in the game, they are assets
the prefab has not collided with anything
cause the game is instantiating that prefab... so i need to change that in all instantiated objects
how could i do that?
Once an object is cloned it has nothing to do with the prefab it was cloned from
it has no connection to it
If you don't want each individual instance of this script to have its own copy of the variable it probably shouldn't be on this class
oh, thanks... ill look for another way to do what i want
could someone explain to me what variable I'm supposed to be clamping on a 3rd person camera? Someone said I shouldn't be clamping the input values and that makes sense. But I'm still not sure which value exactly I should be clamping.
This is a channel for getting help with code
Maybe try all that here:
https://discord.com/channels/489222168727519232/497875120556081172
And then after that, there is no off-topic channel on this discord
Probably read the euler angles and set them to a float. Clamp that float and use it to write back to euler
I'm bad at rotations though, so maybe not.
are you doing rotation? you would clamp the rotation ideally
this is what im working with right now, and I've tried clamping the rotation, but it doesn't work and i dont understand why
inputX = Input.GetAxis("Mouse X") * rotateSpeed;
inputY = Input.GetAxis("Mouse Y") * rotateSpeed;
lookAt.transform.Rotate(inputY, inputX, 0);
desiredAngleY = lookAt.transform.eulerAngles.y;
desiredAngleX = lookAt.transform.eulerAngles.x;
rotation = Quaternion.Euler(-desiredAngleX, desiredAngleY, 0);
transform.position = lookAt.transform.position - (rotation * offset);
transform.LookAt(lookAt.transform);
}```
in my code desiredAngleX and Y are reading the euler angles of the lookAt transform
You're calling LookAt after all that rotation setting...
Oh wait. You're setting the rotation OF lookAt... ok
rewriting camera script when you have cinemachine, is like re-inventing the wheel
- obligatory "just use cinemachine"
- there's no clamping happening here
- don't operate on the eulerAngles from the rotation. track your own float values that you add/subtract to after getting input
for the sake of this project I'm not using cinemachine
could you please explain that last part in a bit more detail
search "clamp camera" in this discord for many examples
if i run string.replace but string is not found does it still gets the string that would be used as replacement?
https://learn.microsoft.com/en-us/dotnet/api/system.string.replace?view=net-7.0
A string that is equivalent to this instance except that all instances of oldChar are replaced with newChar. If oldChar is not found in the current instance, the method returns the current instance unchanged.
ok more exactly
will script error out if string used as replacement will be from invalid index of array
if string to replace was not found at all
if nothing is found, i don't see how it would get the new string to use since there is nothing to use it with . . .
yeah i dont know if second part is executed or no
if oldChar was not found, it just returns the original string . . .
i know it returns original string
there's no need to check newChar if the first part is false . . .
but does script errors out if it has errorprone code in newchar
that's just my guess, you'd have to test it . . .
this question alone doesnt really make sense, "errorprone code in newchar". its a string
or a char
array[-1]
yes that'll be an error..
the string replace will not throw an error because Array will beat it to it
If you want the last element you need array[^1]
time to replace 20 lines of my code with that
dont know what is even this operator but very useful
I assume you are a python programmer π
im so so so sorry somthing came up and i had to go , here are the screenshots.
which can still throw an error
yes that was the point of question
Yep, but -1 will never be valid
array can be empty but i will be replacing using array
but if found then it always be valid
thats fancy
usually you start array from 0
but when ^ then from 1
It takes length-value
length is outside of the array
The compiler uses System.Index which is passed to the array
var lastItem = array[^1]; // array[new Index(1, fromEnd: true)]
although if you're still making stuff for vr chat you can't use that since vr chat uses unity 2019 which does not even support c# 8 where that operator was introduced
i'm pretty sure you have to be targeting .net standard 2.1 to use it at all. i could be wrong about this and it may work on 2021+ when targeting .net framework but it does not work on 2020 and below
This is not set up correctly.
The instructions tell you to update the Visual Studio Editor package to 2.0.20 or later
you will need to remove the "Engineering" feature to unlock the package, then re-install it
oh okay Thank you sooooooo mush! yet again sorry for sending it late! π πΉ
you saved me!!!!!
i was going crazy.
i need some help. im making my first game and i have made a platform with a car on it and some obstacles. But my car just drives thought the stuff also all the things just fall down, ive tried ading a ridgidbody but it dosent work
It sounds like your objects are missing colliders?
Add either a collider2d or collider3d, depending on what you are doing
okay
e.g. a BoxCollider
The same way you've added all the other components you're using
now things arnt falling down but i cant drive up things like rams i just drive through them
hello
How are you moving your player
typically when people ask how you are moving an object, they are not referring to the buttons you press but rather how you actually move it in your code
!code π
π Large Code Blocks
Large code blocks should be posted as 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 get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.
also your !IDE is not configured
If your IDE is not autocompleting code
or underlining errors, please configure it:
β’ Visual Studio (Installed via Unity Hub)
β’ Visual Studio (Installed manually)
β’ VS Code*
β’ JetBrains Rider
β’ Other/None
*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.
a configured IDE is required to get help here
can you help me configure it
follow the instructions
tried what exactly?
to configure my ide
how did you do it?
if the instructions don't work, then you've either skipped something or followed the wrong instructions. because spoilers: ||they do work||
dude ive tried like 5 times
But what exactly
the guide
which guide / which code editor
say useful answers, we're not here to play 20 question if you want help
by code editor you talking about visuial studio or vs code?
You are using Visual Studio
