#💻┃code-beginner
1 messages · Page 614 of 1
Put a log before you invoke the event, and put a log in SetHeadBool. Do both print?
ill check it out
How do you mean? The pool needs to know how to create objects. This function tells it how.
yep
both works fine
maybe that has to do with my bool location?
no sir
Yes, it is
aaaah, ye the code is messed up and
If the log in SetHeadBool is printing, it's setting that bool to true
What makes you think it isn't
well yeah, I just find it weird that its just a () and nothing else
it doesn't matter tho, I'll do more research on this later
Are you looking at the instance you're actually changing the bool on
Whichever instance you dragged into here
how do i change it to true instead of on
...?
You are changing the bool to true. This is not in question
The object you've dragged in to that event is getting its bool set to true
Is that the object you're looking at
[Serializable]
struct Projectiles{
public Projectile projectile;
public int minProjectiles;
public int maxProjectiles;
}
[SerializeField] List<Projectiles> projectileInfos;
List<ObjectPool<GameObject>> ProjectilePools;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
for(int i = 0; i < projectileInfos.Count; i++){
int temp = i;
ProjectilePools[i] = new ObjectPool<GameObject>(
() => CreateProjectile(temp),
OnReturnedToPool,
OnTakeFromPool,
OnDestroyPoolObject,
false, projectileInfos[i].minProjectiles, projectileInfos[i].maxProjectiles
);
}
}```
so hopefully this works
I just also need to make it so that it pre-generates all the objects beforehand
otherwise I get lagspikes when they are first created
GameObject[] premadeObjects = new GameObject[projectileInfos[i].minProjectiles];
for(int j = 0; j < projectileInfos[i].minProjectiles; j++){
premadeObjects[j] = ProjectilePools[i].Get();
}
for(int j = 0; j < projectileInfos[i].minProjectiles; j++){
ProjectilePools[i].Release(premadeObjects[j]);
}```
this is also just such a stupid hack
i think this is pretty similar to what you're making. the netcode team has an example of a kinda global object pool, just swap out anything netcode related with whatever type you want.
https://docs-multiplayer.unity3d.com/netcode/current/advanced-topics/object-pooling/
in what way lol, this is quite literally how you pre generate objects. if you want to spawn them, they have to be spawned
isn't that what I'm doing?
its just that the defaultCapacity parameter of the objectpool constructor makes like 0 sense if you have to do this anyway
ok so my prefab is getting its bool set to true but not locally? im really trying to understand
well the first thing i wrote "i think this is pretty similar to what you're making". maybe actually click the link and look through it 🤷♂️
Whichever object you dragged into the inspector is the one you're calling the function on
If you dragged in a prefab, you're calling that function on the prefab
yes, I looked through it, this seems like the exact same thing but for netcode
i dragged the script, don't all the scripts change?
whoever gameobjects the script is attached to
I don't understand the difference
If you dragged in the script, you wouldn't have been able to call any functions on it
because MonoScript doesn't have any functions. It's a text file
You drag in an instance of a script, which is on a GameObject
That's not dragging in a script. That's dragging in an object
You are telling it to call the function on that Cowboy
i understand
well its clearly not the exact same thing if you look at the code (excluding the networking part even). i sent it so you can have a guide on how to organize/improve your current system
Also I was writing it before you sent that last code part of pre generating objects
i used it as a guide for my own object pool too
but why does everything else works besides the boolean
i tried to print it in the update function
and its never set to true
I'm sorry, I just can't really figure out which part is relevant and which part isn't
check ur conditions.. how many conditions have to be true for the bool to be true?
debug each one.. figure out which one is not working as desired
because I only really saw the objectpool functions that werent netcode related
it doesn't
- The Boolean is working
- If you're calling other functions on this same object, they're being called on that object, not any others
appareantly you cant even do this
How can i make a ring??
Contact Sauron
I create and I release them
most of the code there doesnt need to be specific to networking, you can replace Network object with like GameObject or whatever component you want. the spawn/despawn could be your own functions or enable/disable
u can start with an old coin.. u punch a center hole in it.. and use a lathe to bore it out
so if i invoke the function in the bullet, it will be called on the bullet obj?
Whenever the object with this script on it collides with an object tagged "Head", it will call SetHeadBool on the object you dragged in for that event.
Whenever the object with this script on it collides with an object tagged "Torso", it will call TorsoHitFunction on the object you dragged in for that event.
I mean in unity
still need more information
well you usually model stuff in a modelling app, not in Unity
u can use probuilder. but blender is my recommended as well
anyone know how to fix this?
or maybe a better way to do it?
i really don't see the problem with the code
What problem?
i swear im trying to
We've established, the boolean is getting set
the bool is never set to true
It's doing exactly what you told it to
it's getting set to true on the object you've dragged in
"thats a torus
"
Can i use this 2d?
id probably look for a model on the asset store if u have zero modelling experience @boreal umbra
just draw one
mspaint enthusiasts rise up
also Unity Asset Store is CHOCKED full of 2D sprites
im sure u can find a ring on there
Thanks bro
Kenney nl has good stuff
fun fact: mspaint got AI before we got GTA6 🙂
no problem.. Good Luck finding what ur hunting for 🙂
https://itch.io has good assets too
it is never true
might look there as well as kenny
On this instance maybe
Fix what
But it is getting set to true on the instance you dragged in
can he use Context in a debug to find the instance its changing?
We know what instance it's changing. They've already said it's a prefab
ahh okay 👍
I'm just trying to explain that the prefab and the object in the scene are not the same Cowboy
ahh! one of those.. roger that 🫡
LMAO WHAT
i mean i use win10
its paywalled tho 😦
i just thought it was kinda wild.. since mspaint been nothing but vanilla for ages
also the dark theme
holy fuck i cant figure this out at all
no matter when I release all the projectiles, they just get destroyed
want to make a thread?
this is the last thing I need figured out, so idk if itd be worth
the rest I can handle myself
hopefully
the only suggestion i have w/o digging deep into it would be to debug everything possible.. follow the logs.. until u see something that doesn't seem right
I haven't been following this at all but remember, if you do something like someArray = aDifferentArray, that doesn't copy the array it makes both variables point to the same one. If you've got anything somewhere where you're doing expecting to modify aDifferentArray but have someArray stay the same, that won't work
I don't know if that's a problem (there's a lot of context) but you're doing array stuff and from what you describe the wrong things are being referenced
GameObject[] premadeObjects;
void Awake()
{
for(int i = 0; i < projectileInfos.Count; i++){
premadeObjects = new GameObject[projectileInfos[i].minProjectiles];
for(int j = 0; j < projectileInfos[i].minProjectiles; j++){
premadeObjects[j] = ProjectilePools[i].Get();
}
}
}
void Start()
{
for(int i = 0; i < projectileInfos.Count; i++){
for(int j = 0; j < projectileInfos[i].minProjectiles; j++){
ProjectilePools[i].Release(premadeObjects[j]);
}
}
}```
this is what I'm doing rn
yeah, but microsoft :/
oh wait
I can see the issue
fuck
you were right
its not what I meant to do
I don't know how to do it though, I basically need a list of lists
helo, how do I send code in this form
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Inline coding
// //The MonsterCloseScreenEffect start coming in the closer the monster gets.
int Minmin = 0;
int Maxmax = 20;
int test = (int)Mathf.Lerp(Maxmax, Minmin, dist);
float lerpedMonsterCloseSE = Mathf.Lerp(MonsterCloseSE_START_AMOUNT, 1.25f, test);
_materialMonsterCloseSE.SetFloat(_MonsterCLoseSE, lerpedMonsterCloseSE);
Helo, I have some code here that should change material float based on "dist" . dist is an int and its how close the player is from another object simply(x to 0 and 0 being im next to the object). What im trying to achieve is the closer the player gets, the more the material float should smoothly change until I'm next to the game object and the material float hits its target 1.25f. In my code im trying to start tracking the dist at 20 and see if player is getting closer so i can smoothly change the float.
I already havve dist working somewhere else fyi
{
Debug.Log(projectileInfos);
}
wtf?
shouldnt this be at least debugging Null if it didnt exist?
I don't get anything logged
you want InversePerp for that first part, and a float not an int
Null doesnt print "null", it just prints an empty string
float t = Mathf.InverseLerp(Minmin, Maxmax, dist);
float lerpedMonsterCloseSE = Mathf.Lerp(MonsterCloseSE_START_AMOUNT, 1.25f, t);```
@faint agate
well, shouldn't I still have something popping up in my console?
cuz rn I don't get anything
as if my start function was completely ignored
then the object is not active in the scene
Then this script component does not exist in the scene or is not active
Awake does get called though?
Awake works, Start doesn't
even though the object is active
then the component is not active
and no errors show up
hold up, wtf
something is disabling my object
nevermind, im stupid
ty for the help tho!
no wonder it didnt release
now for some reason my OnDestroyPoolObject is being called instead of Release....
thank you, i was look for something like InverseLerp for so long, exacly what I needed.
i felt close 😭 🫡
sooo useful.. one of my favorite methods of all time..
soo often im taking a min and max and remapping it to some other range..
so my objects get returned and immediately destroyed for no reason
ObjectPool<GameObject> objectPool = new(
() => CreateProjectile(temp),
OnTakeFromPool,
OnReturnedToPool,
OnDestroyPoolObject,
false, projectileInfos[i].minProjectiles, projectileInfos[i].maxProjectiles
);```
https://pastebin.com/3dp1V6Nz
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
in this case, minProjectiles is 10 and maxProjectiles is 100
first I get 10 returns, then 10 destroys
That sounds like your pool maximun is set to 10
Double check your parameters with debug.log
i doubt that it should be destroying ALL of them, still
ill try that
nope, its correct
Destroy should only be happening if you try to return something to the pool and the max number is already in the pool
yeah, exactly
which is why I'm confused
Debug.Log(projectileInfos[i].minProjectiles);
Debug.Log(projectileInfos[i].maxProjectiles);
int temp = i;
ObjectPool<GameObject> objectPool = new(
() => CreateProjectile(temp),
OnTakeFromPool,
OnReturnedToPool,
OnDestroyPoolObject,
false, projectileInfos[i].minProjectiles, projectileInfos[i].maxProjectiles
);```
10 and 100 gets printed
so I seriously don't understand
I can even remove the projectileInfos[i].minProjectiles, projectileInfos[i].maxProjectiles part
it doesnt matter
still gets destroyed
seriously 0 idea what's going on
this is all I get
Have you used a debugger yet?
I use object pool often but I usually just define the construction, get and release functions and its fine.
i tried debugging the values but you cant really debug a constructor
i guess that works
thanks for that!
How could i achieve this: from the main canvas you press enter, you switch to the first level selection ( 2nd canvas ) you scroll down and can go to the 2nd one, and scroll up if you want to go back, and enter to select the level, how would you guys suggest me to do this?
my code ( https://scriptbin.xyz/ocofiwadet.cs ) is still not working so i want to try other ways
Use Scriptbin to share your code with others quickly and easily.
simply use 1 script..
go to this scene when Enter is pressed..
use that script on all ur canvas's
whichever one is enabled has the version of the script that goes to the scene u want it to..
i tried using if statments but it wouldnt go to the next scene
sorry if the question is dumb but how would you do it
How do i use JsonUtility.FromJson with a list?
the list cannot be the root object, it must be part of some other struct or class
i foudn a helper online but that didnt work either
it is tho
the list cannot be the root object
as in, JsonUtility cannot support that
why u need if statements?
i hate unity sometimes
what im saying is use (1) script
using UnityEngine;
using UnityEngine.SceneManagement;
public class EnterKeySceneLoader : MonoBehaviour
{
[SerializeField] int sceneIndex;
private void Update()
{
if(Input.GetKeyDown(KeyCode.Return))
{
LoadScene();
}
}
private void LoadScene()
{
SceneManager.LoadScene(sceneIndex);
}
}```
u can change the sceneIndex to w/e u want.. each canvas having its own version of the script.. w/ the scene that corresponds assigned
no but some packages use it as a dependency so it might already be installed, otherwise you can just install the package
it works the same as any other c# project? like just using nuget?
it's a package you can install via the package manager
oh okay
what using arrow up/down to scroll beetween 1 level or another
yeah the first part i managed to do it, the arrow keys part didnt work
but say they're big UI Panels..
with the art and description or w/e
you could enable it off screen or enable it right when u need it
then i made that over complicated script which didnt work
i had smth around like, all the canvasses off except the main screen one, and than if you press enter you go to the 1st option,but i didnt manage to make it scroll up and down or select again
something like this is what iwas thinking... (the ones off screen technically dont need to be enabled until ur ready to use them)
soo if that were the case.. then just having different version of the script on each Element that u enable/disable would be simple enough
or, you'd need a bigger system keeping track of which one is focused/selected
is it this?
it feels like thats not it
and then u'd check using a switch statement.. instead of a big ole nasty if-else chain
switch case?
oh u are keeping track of what canvas is selected and using a switch statement
why the issue w/ loading a scene with that?
no idea it doesnt work
what about the log?
the debuging only managed to show that on enable was on
i see that its this but idk how to install https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@3.0/manual/index.html
so no
Debug.Log("EnterPressed is working");
?
nop
if onenable runs and that doesn't then no input is received
yeah i thought it was something with input thats why i did #🖱️┃input-system
but idk how can i make it work
yeah same
i would continue there tbh
or try re-creating ur map and trying again
im working with a few classmates that use it but they dont know the error too
how would you do it without the new input system?
How do i install this package? this is super confusing
i tried EnterPressed () and didnt work i had to add that part to make it work
i mean
not show a error bc it didnt work xd
Try #💻┃unity-talk
i think i got it finally
1 - check ur maps
2 - check the inspector if ur using the InputAction thingy
3 - maybe check the input debugger
private void Update()
{
if (Input.GetKeyDown(KeyCode.Return))
{
Debug.Log("Enter key was pressed!"); //EnterPressed();
}
}```
Will Invoke(method, time) sync up with a timer like this:
if (timeLeft > 0)
{
timeLeft -= Time.deltaTime;
}
Called from different places, unrelated
Probably not. Two copies of that same script won't even necessarily sync up
Floating point precision being what it is
You're never going to be able to make a timer more precise than your framerate
So, as long as you can get them to sync up on the same frame, it should be fine
i dont think thats necessarily true, at least if this is just on one pc
if you're doing the same math across different instance, the results should be the same. the results just may not be precise to what the actual answer should be
this is what i mean, the results are the same but floating point precision makes the result wrong.
https://dotnetfiddle.net/1h21m1
floating point precision isnt like a randomness that each float gets affected by
I was thinking maybe stuff would get rounded differently due to imprecision, but you're right, they'd all get rounded the wrong way. So they'll sync with each other, but might all be a different time than you expect
online sources say that different devices might get rounded differently, so it might be an issue in like multiplayer or whatever other use case
I always wondered how true that is but I really cant be bothered looking so low level
well with native code it can differ what instructions are used between compilers but if its still mono id expect this to be consistent
var rounded = Mathf.Round(value);
cooldownText.text = value.ToString();
How can I get it say "3.4" instead of just "3", but also not "3.4575317", if you get what I mean, im not really sure how to even search this up.
Dont wanna be annoying with these sort of questions so I apologize.
If you chuck “F2” in the param of a .ToString() it should work iirc? ToString has a variety of formatting codes
Interesting, thanks for that
Aside from making my own UpdateManager that handles it, is there a direct way for things to subscribe and unsubscribe from Unity’s runtime update loop?
Perfect, thank you, thats got a lot of useful formats
Will have to look into this but just general vibe check, is this overkill for just various mechanics coming and going performance wise or is it pretty flexible
Wdym by "various mechanics coming and going"?
In general for normal game stuff it's overkill yes.
It's usually more useful when you're doing something special like a custom network framework or custom hardware based input or something along those lines
guys why does flashlight camera and character get bugged like they turn insanely speed when i write this code in flashlight
IEnumerator FollowCamera()
{
transform.rotation = Camera.main.transform.rotation;
transform.position = Camera.main.transform.position;
yield return null;
}
why is that a coroutine? it runs those two lines of code and then waits to do nothing
Whenever that function is called, this objects position and rotation will instantly be set to the camera's
remember, coroutines do not delay the code they are started from (with the exception of yielding the StartCoroutine call in another coroutine)
i wanted to make that the flashlight follow the camera a lil delayed and i wanted to add yield return new WaitForSeconds (.5f) so camera would turn like delayed
well right now this coroutine won't delay anything
so what thats what i want, or?
yeah it doesnt
Then what's the problem?
You want it to snap to the camera? It is
They're snapping directly to whatever the camera's rotation is
If that's, like, 180 degrees, it's gonna flip instantly
what does it mean to "turn insanely speed" because right now it will follow the exact rotation and position of the camera
insanely uqick
How do i know when im ready for a game jam?
Yes.
#🕹️┃game-jams (see the pins in that channel too)
i mean
finish a thought before sending a message
it looks to up down right left
even tho i dont turn
it is doing exactly what your camera is doing
i write it so u can understand that im not afk and its better for me to speak that way
i know but
oh thanks ill move my post there.
If this object is doing anything other than snapping to exactly the main camera's rotation, it's not this code doing it
but when i delete that part
the problem goes off
Have you considered the possibility that you're snapping between two points every frame and that's causing it?
In that case, getting rid of either snap would fix it
Maybe you should share !code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
thats all the code of flashlight
using System.Collections;
using UnityEngine;
public class FlashlightScript : MonoBehaviour
{
public bool hasFlashlight = false;
public KeyCode flashKey = KeyCode.F;
private GameObject character;
private GameObject Flashlight;
private Light Light;
private void Awake()
{
character = GameObject.FindGameObjectWithTag("Character");
Flashlight = character.transform.Find("Flashlight").gameObject;
Light = Flashlight.GetComponent<Light>();
}
void Update()
{
if (Input.GetKeyDown(flashKey))
{
ToggleFlashlight();
}
StartCoroutine(FollowCamera());
}
void ToggleFlashlight()
{
if (hasFlashlight && Flashlight != null)
{
Light.enabled = !Light.enabled;
}
}
IEnumerator FollowCamera()
{
transform.rotation = Camera.main.transform.rotation;
transform.position = Camera.main.transform.position;
yield return null;
}
}
For one, that coroutine does nothing, you can just put those two lines in update.
Take a screenshot of your unity window, with this object selected and visible in the hierarchy and inspector
i wanted to make that flashlight follows the camera delayed so i wanted to use wait (.5f) so it would turn the flashlgiht to the cameras position delayed
btw just adding a waitforseconds isn't going to give you the behavior you want because after the wait, it will still snap to the exact position and rotation of the camera
like that?
Hey, I want to give an angle to an image in script, do I have to use quaternions for that?
Okay, so, the camera is a child of this object
And this object's rotation is rotating to meet the camera
which means the camera is rotating to maintain its relative offset
how would i make it so that an animation plays only when the gameobject hits a certain Z-cord?
no it does, after .5sec it will go to my cameras pos
normally it wasnt
using an if statement
It will wait .5 seconds, then go to where the camera currently is
But that's not the issue
Since you don't even have a wait
yeah that gives the delay
Right now, your issue is that your camera is chasing its own tail
lol that's for sure not the delay you are thinking of. but focus on your current issue
but normally flashlight was in the char
Okay, what does this have to do with anything
now it doesnt turn exact with the camera if i wouldnt write the code
and my char tp's so somewhere else when i start the game, when i add this code
...what?
Not sure what I'm supposed to be looking at here
normally i supposed to be in this hous thing
but i tped here
im in void
when i add rotation code
Are you still snapping the object to the position and rotation of one of its children
because if so that's gonna cause all sorts of problems
As I said, the object with this script on it is a parent of the camera, and it's snapping that object to the camera's position and rotation
child objects maintain their relative position and rotation from their parent as the parent moves
So your object is pulling a Lorax and lifting itself up into space
the flashlight is not the child of the camera
as i said
Did you move the script?
So the script is still on the parent object
at the new photo
and nothing has changed
i wanted to show u
the script is on the player object yeah
Which is a parent of the camera
yeah
So you haven't fixed the problem
Don't make an object snap to the rotation of one of its children
Okay, let's do a demonstration. Stand up, hold your left arm out to one side.
Now, keeping your arm stiff and straight out, spin your entire body until your are looking in the directon of your arm. Do not twist your hips or move your shoulders, only use your feet to turn
huh
but flashlight is not the parent of the player
It's an utterly unrelated object to the problem
The flashlight object has nothing to do with this
you're rotating the player object, which is a parent of the camera, to the direction the camera is pointing
im looking with my head
but i guess i got what u mean
hold up
No rotating shoulders, hips, or arm
You keep your arm straight out
Use your feet to rotate your whole body until you're looking in the direction of your arm
Do you ever actually reach it
or do you just spin there with your arm out forever
That is literally exactly what you are doing which is why I said so
in flashlight script right?
Every frame, you snap the player object to the rotation of one of its children
Yes, the script we've been talking about the whole time, that one indeed
no i dont
Literally yes you do
i snap the childrens pos to the player object
wait
NOOOOOOOOOOOO
I GOT IT NOW
I TRY TO ROTATE THE PLAYERRRR
NOT THE FLASHLIGHTTT
now instead of turning player which i made it wrongly normally i wanted to rotate the flashlight, i rotate flashlight
yeah
I hope you appreciate the red marker I did that freehand with a mouse
i do
i really appreciate bro
tysm for helping me
and taking time to help me
i have 1 more question
Flashlight.transform.rotation = Camera.main.transform.rotation;
this flashlight's transfroms rotation doesnt turn to cameras rotation
"The referenced script (Unknown) on this Behaviour is missing!"
what does this message mean?
Is the flashlight object still a child of the camera
even tho i rotate my camera when i look at the transform, the transfrom rotation position is 0 why?
no child of the player
it means you have a broken component attached to your GameObject. Probably a script you deleted or something
alright
should i just delete the gameobject reupload it onto the scene and attach all the components again?
Just remove the broken component
i did and it still gives me the message
Then you have more than the one
let me check rq
ah it fixed
but that didnt change the base problem I have
I'm trying to make it so that my gameobject only plays its animation when it reaches a certain Z coordinate
Y cord i mean
if statement
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
public class ShackleUnlock : MonoBehaviour
{
private Animator animator;
[SerializeField] private string animationTrigger = "PlayAnimation";
void Start()
{
animator = GetComponent<Animator>();
if (animator == null)
{
Debug.LogError("Animator component not found on this GameObject. Please add one.");
}
}
void Update()
{
if (transform.position.y <= 0)
{
if (animator != null)
{
animator.SetTrigger(PlayAnimation);
}
this.enabled = false;
}
}
}```
Log when you set the trigger, see if it's running
which debug code is that?
I'm sorry I'm a super beginner
Debug.log()
Debug.log(nice)?
would that work?
Debug.Log should literally have been the first line of code you wrote
I think
animator.SetTrigger(PlayAnimation);
should be
animator.SetTrigger(animationTrigger);
alright let me try that
yea I just put it there
Is this code not highlighting in red for you?
in your code editor?
no
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
• :question: Other/None
Follow the link for the one you're using^
there should be a test to prove your ide works to talk in this server 😆
This original problem was happening btw because you have a compile error
alright
and the reason you have a compile error is because your code is wrong, and it would be showing the error in the unity console
im on mac so aight
im downloading vscode rn
you also likely won't get your IDE working properly until after you get that compile error fixed, ironically
so you'll need to fix it first
This should fix it
i changed it
That reminds me the time someone refused to configure their IDE so when everyone refused to help until they proved they did, they went and grabbed a screenshot of an IDE from StackOverflow and tried to pass it off as theirs.
The kicker? The screenshot was of an unconfigured IDE.
In a question about why it was not configured
so after I download VSCode and fix all the compiler errors I'm good?
ha the lengths some people will go to
just configure atp
You need to configure VSCode too by following those instructions linked
alright
Absolute peak
How do you mess up that bad lmaoo
my unity preferences vanished wth
nvm it just changed places
web builds does not update depending on computer framerate
@wintry quarry i got it configured
But its not showing any errors I made on my code
do you have errors showing in the unity console?
show a screenshot of your unity console
Like i said earlier you may have to fix all your errors before the configuration gets picked up properly
from there on it will highlight errors
theres bugs in the console that im trying to find
it should be in the animator
you don't have any compile errors right now
so there's nothing that would show in the IDE
You mean these?
click on one of them to see the full error message
it will say where in the code that is
actually nvm I know where it is
You would have to show your animator window
to show what you named your parameters
Your animator doesn't have anything by that name
okay
@wintry quarry some thing else came up
yeah yeah we know that part
show your animator
actually that's looking like now you're trying to use ResetTrigger on a parameter that is not a trigger
so again - showing the animator will help
btw when I try to add a motion it wont let me add the animation of the lock opening
because its legacy and not generic
i made it a float
it should be a trigger if you want to use REsetTrigger with it
that is also not a trigger
yep
i fixed it so its a trigger now
its still doing it automatically
but the fact that I can't add a motion to the animator state because of rig might be why
Does your transition actually check the trigger
no
So why would you expect setting the trigger to have any effect on the transition
im fixing it hold on
whats the approach for pooling different bullets or is it good idea to try to pool different bullets
hey peeps
perhaps not so much in unity
but in general is CUDA a good skill for an aspiring game dev?
I am a senior web dev trying to change careers
GPU algorithms have me fascinated at the moment but not sure what I could actually do with them
Yeah, it's a good skill. Unity has its own wrapper around it called compute shaders, but in general it's useful
it also gets you thinking in the massively-parallel way
not terribly useful unless you want to specialize hard.
most gamedev is not dealing with compute shaders unless you make something thats never been done before on a large scale
i already did so
building a standalone raytracer atm
i guess i have a solution looking for a problem kinda situation
i just want to learn compute shaders / massive parallelism
thanks exactly what i meant
i probably know the problem tho
I have no animation in the motion section of my Play Animation animator state
and I cant put one in because my animation is in legacy not generic
yes that's what the third warning is about
a common use case for compute shaders is VFX Graph (particle effects) and GPU based instancing & rendering without CPU involvement (say for grass on terrains), and similar situations. But obviously, both are "solved" problems
yea but when I change it to generic theres a whole lot of BS I gotta do
brb
I used compute shaders and the job system for a Satisfactory-like game to handle t he items on the conveyor belts (of which there could be millions)
I really think that satisfactory should have cut a lot of the logic on thebelts considering how easy they desync with multiplayer
no clue how it's all serialized, but they work for maybe an hour then you need to restart the server
do you use compute shaders only for the rendering part or also simulation?
I think it works a lot better now than it did at the early access launch
rendering
the simulation is all jobs
oh yeah totally, that game was very unplayable in the betas for multi
but getting all the positions and rotations right for rendering is a compute shader
they probably have made no particular effort for it to become a multiplayer game
so basically a instanced indirect renderer?
it was their selling point, well, the alpha release video had it in the spotlight
exactly. Dumb video of it in action here: https://www.youtube.com/watch?v=ve0rtD7KUNQ
I abandoned the project for a few missing URP features a while mback
Just playing around with Cinemachine Dolly Cart in my untitled factory builder game. The camera movement is pretty janky, I know!
maybe I'll pick it up again later
one of the selling points, it does well as a single player game
nice, been toying with the idea... but havent yet thought about the rendering part
factory games are still an enigma to me. Having this huge world where you're constantly calculating some product, but it needs to be stateless because otherwise it wouldnt be playable
they arent stateless
definitely not stateless haha
you just need a neat way to query the simulation and only display and fully simulate the visible part of it
the primary issue they have, performance wise, is that they are graphs, and graphs have issues with data locality
I was thinking it just calculated everything only when you're in range, which would take in account of the time you previously visited
@wintry quarry I changed it to generic and it doesn't play but when it gets to the required y coordinate the animation still doesn't play
oh no, they simulate everything all the time
couldn’t factorio be a grid?
yes, thats one of the constraints they rely on for optimizations
they actually do have locality
in satisfactory belts have a limited length, also creating locality
then you often have limits on how many edges can be attached to a node, allowing you to use fixed size buffers
found the problem
but even without locality, absent visuals, you can still heavily parallelize that stuff and run it on background threads, so little impact on FPS just from the sim
i am tempted to make a city simulation (not really a game) using cuda. see how far i can get before i give up
just stuff enums into textures (enums if cuda. my cpp is pretty good)
not working on a product just learning
very fun project, very difficult
great for learning
you need to be careful with cpp-thinking, can be helpful in some places and misleading in others, depends a lot on what kind of cpp it is
@polar acorn hey
I'm trying to port a sort of cities skylines clone of mine from c++/opengl to Unity and I'm mostly a Unity noob
Can someone clear up a few things for me?
-Can't really use most of the editor, since everything is created by the user, there are no 'scenes'
-I can't really use GameObjects + MonoBehaviors because of performance (will likely switch to ECS)
-Can't really use the normal importing pipeline because I want users to mod in custom assets (ideally without needing the UnityEditor)
-Can't use Prefabs since you can't create them at runtime
-Can't use ScriptableObjects since the user can't change them at runtime
Anything I'm missing?
thanks a lot for the help
ive figure it out that i needed a static variable
and that it was only affecting the prefab
sorry about this morning
I will basically have to find a good importer library, handle meshes/textures myself and instantiate gameobjects/ECS entities myself, right?
Currently I'm a bit paralyzed because I was planning to write the classical unity way of doing things first, then profile and slowly port to a ECS implementation which handles assets at runtime, but just trying to automate importing assets using GLTFast seems to require me to switch to the fully custom approach instantly
Well, you'll find that most existing engines follow the same approach. Importing assets from raw files at runtime is not a common feature in games and requires you to incorporate sdks and frameworks, that are usually part of development tools, into the actual game.
Other than that you mostly assume correctly. The only thing that I should note is that you will still need scenes. Or at least one scene. Since your game actually need to run in some space.
Honestly, it sounds like maybe a full game engine isn't a great approach for you
Might want to look at some engines that only provide rendering capabilities.
Yes, I do find writing simulation heavy code probably benefits more from c++, at least if you can grog the language
The main things I wish to utilize are the rendering backend, and some general quality of life that the engine would ideally still provide
Like I implemented PBR and bloom pretty well, but my shadowmapping was bad and I had trouble implementing LOD and culling efficently for huge numbers of instances
Supposedly ECS + UWP has a good implementation for me
I do understand that ex. decoding pngs at runtime is bad (though many indie games seem to do that actually), for most games it makes sense to do it the unity way
But I still feel like they could allow to include a few common import/exporters in the build as an option, and allow packing runtime-loaded assets into bundles you can save
Im not sure what problems this would cause other than giving you more code to ship and it being a bit slow if you do it on startup
They do offer runtime loaded assetbundles, just not without editor involvement
In theory I suppose it’s possible to create them yourself but i think that’s maybe against some aspect of unity tos?
Well. It simply isn't a priority for them. Maybe one in 10000 or less games need something like that. And they are probably not even being unity's main client(games and studios that unity actually profits from).
What aspect of a prefab are you worried about creating at runtime?
People did suggest shipping a unity scene to act as some sort of SDK, which could produce bundles which could then be shared
Which is not a bad model, especially for real mods
It's mainly just if you want to make adding custom assets more convenient
Though it's a bit weird how i my own c++ project, I can basically just add an fbx, a the textures and an entry in a json, and have a custom vehicle asset, (All with nothing but json deserialization and a mesh and image loader)
but in unity you need a whole involved process to achieve the same thing
Well, if your engine was as complicated as unity or unreal, you'd probably have something similar. There are many layers of abstraction required to handle many different cases, as well as to protect the game assets to a degree.
right now, loading meshes
I'm trying to use GLTFast, but keep running into issues
I think it's because I'm trying to do a hybrid thing where I can use my assetmanger both in editor mode and at runtime
Yeah Meshes are the one major thing that come to mind for something like this
everything else is pretty manipulatable at runtime
(i'm the author of a fairly big custom content api for a popular unity game so i know a handful of things about this kinda jank :P)
May I ask which one?
LethalLevelLoader for Lethal Company
Oh hey, I've recently got into lethal!
Amazing game and amazing mods, though I haven't tried custom level yet
even uploaded a very simple 'more scrap during weather' mod because the two I found were broken myself
Oh nice 😄
But yeah it uses assembly injection and assetbundles to allow authors to make custom levels, interiors, enemies, items etc. without the need for custom code
The workflow is pretty rough given that the game wasn't designed for that kind of thing but there's a lot you can do for this kind of thing
inputActions.Player.Look.performed += ctx => mouseX = ctx.ReadValue<Vector2>().x * rotateSpeed * Time.deltaTime * mouseSensitivity;
``` Do I need deltatime here? This is in the `Awake()`
could someone help me with this animation
im trying to make it so that it only plays when it reaches a certain y cord
but the animation just doesn't play when it reaches it
I'm a noob myself, but:
mouse deltas are in delta pixels since last frame so no delta time - > lookAngle += delta * sens
gamepad stick input can be seen as a analog velocity -> lookAngle += analog * speed * dt
Not sure why you put anything in awake though?
it is a delegate called by unity when you pressed something
dont crosspost #📖┃code-of-conduct
ah, got it, i'll take it down
could someone help me with this animation its supposed to activate when y <= 0 but when it reaches that point it doesnt play the animation
right, either way, I think for normal camera controls you want to have a Vector2 lookAngle; and then modify it with += every frame scaled by deltaTime for gamepad/keyboard (but not for mouse!)
but I'm not familiar with the event-based input patterns, sorry
aw man no ones helping me im cooked
its been 8 minutes, this is a coding channel and you havent given any specific details to your problem. how is anyone supposed to help
alright let me give specifics
so im making a lock opening animation and basically you have to click on it and it moves down along the y-axis
when y <= 0 its supposed to play an opening animation
look at the #854851968446365696 on how to ask, please have all info just ready in a paragraph
but when I click enough for that to happen it doesnt play the animation
ok
what's a way for make "object a" modify a value from "object b" or make it enter into an state?
i mean, i know how to do it "if they are being touched" but not if not
like this, but with only happening if this thing gets activated
{
if (collision.transform.TryGetComponent(out EnemyBase enemy))
{
enemy.TakeDamage(riflebulletdamage);
Destroy(gameObject);
}
}```
Reference object b in object a
how specificly?
However you want. What's the relationship between these objects? They surely connect in some sense at some point, right?
its the enemy and the player, my idea is that when an enemy dies i want it to make the player get one point of an int value called "valeriapoints"
Well, does the player know of the enemy at some point?
elaborate... i mean, technically only in this part
if (hitEnemy != null)
{
if (hitEnemy.TryGetComponent(out EnemyBase enemy))
{
enemy.TakeDamage(meleeDamage);
}
}
if (hitProyectile != null)
{
if (hitProyectile.TryGetComponent(out MortemRifleProyectile enemy))
{
enemy.Parry();
}
}
}```
its when the overlapbox of the meele touches an enemy
causing it to enter into that state
and well, the rest is history
Ok, so it depends on what combat system you have. Some games would lock 2 characters in combat each one would have a field for "current target or something".
Alternatively, if it's something that needs to be done on character death(which is presumably caused by the other character attack), the attacking player reference could be retrieved from the attack data.
its a plataform run and shot
You could also cache all the enemies you hit or got hit by in the last few seconds, minutes, and when a character dies, it let's all the people that hit it lately know.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class KillCounter : MonoBehaviour
{
int kills;
int scary;
public bool gotkilled;
public bool BuffReceived;
UI_Bars HealthScript;
DealDamage DamageScript;
public TMP_Text ScaredText;
public TMP_Text KilledText;
// Start is called before the first frame update
void Start()
{
BuffReceived = false;
HealthScript = GameObject.FindWithTag("Player").GetComponent<UI_Bars>();
DamageScript = GameObject.FindWithTag("Player").GetComponent<DealDamage>();
kills = 0;
scary = 0;
}
// Update is called once per frame
void Update() {
if (scary >= 5 && !BuffReceived) {
HealthScript.Buffff();
BuffReceived = true;
}
if (kills >= 5 && !BuffReceived) {
DamageScript.ReceiveBuff();
BuffReceived = true;
}
KilledText.text = kills.ToString();
ScaredText.text = scary.ToString();
}
public void AddKill() {
kills++;
Debug.Log("killed" + kills);
}
public void AddScare() {
scary++;
Debug.Log("scawwed" + scary);
}
}
so the Debug.Log works fine ingame in the console but idk why the tmp is like buggy? sometimes it get stuck. not even at the same number.
You can also subscribe to a events on a character that you hit, so that when it dies, you receive an event.
h o w
that sounds usefull af
Well, you already have an attack mechanic, so you have the reference at that point. Add it to a list along with a timestamp or something. Then in update, check the timestamp and of it has been too long, remove the reference from a list.
Very simple.
Instead of passing just a numeric value in TakeDamage, maybe make an ReceiveAttack method that you pass all the relevant data(including a reference to itself) in some kind of struct.
Then the other character can do whatever you want with it.
but what you mean with a struct?
wat
This is C# basics. I suggest you go over the C# basics before continuing.
I mean, it could be a class as well. But structs fit better here to avoid needless heap allocations.
(same question but its more clean) so the Debug.Log works fine ingame in the console but idk why the tmp is like buggy? sometimes it get stuck. not even at the same number.
Please share !code properly:
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
And explain what you mean by tmp being buggy.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class KillCounter : MonoBehaviour
{
int kills;
int scary;
public bool gotkilled;
public bool BuffReceived;
UI_Bars HealthScript;
DealDamage DamageScript;
public TMP_Text ScaredText;
public TMP_Text KilledText;
// Start is called before the first frame update
void Start()
{
BuffReceived = false;
HealthScript = GameObject.FindWithTag("Player").GetComponent<UI_Bars>();
DamageScript = GameObject.FindWithTag("Player").GetComponent<DealDamage>();
kills = 0;
scary = 0;
}
// Update is called once per frame
void Update() {
if (scary >= 5 && !BuffReceived) {
HealthScript.Buffff();
BuffReceived = true;
}
if (kills >= 5 && !BuffReceived) {
DamageScript.ReceiveBuff();
BuffReceived = true;
}
KilledText.text = kills.ToString();
ScaredText.text = scary.ToString();
}
public void AddKill() {
kills++;
Debug.Log("killed" + kills);
}
public void AddScare() {
scary++;
Debug.Log("scawwed" + scary);
}
}
what i mean with buggy is when i kill the enemys the counter works fine (as well as the debug function)
but the Scare Enemys counter stops randomly counting (stuck at 0,3,4) BUT the debug function still counted correctly
I don't see anything wrong in this code.
Can you record a video showing the issue with the logs visible?
which tool is good for recording?
If the debug has the correct count, then it works. Is there a problem with viewing the number (visually) during runtime?
obs or sharex
not really? i think its just an simple counter which goes up to 4 like 0,1,2,3,4 but then stops
did the video got compremised?
Well, you are constantly receiving an error in KillCounter . . .
You're getting a null reference error. You need to make sure the variable is assigned. Yes, you assign it in Start, but it can still be null if nothing is found . . .
I dont wanna sound stubborn or sth but i wanna understand „why“ like the debug works and im working with the same int?
(Trying the fix the null error rn)
We don't know why yet; that's what we're finding out. If it is assigned in Start, then somewhere during runtime, it's removed or deleted . . .
Because errors in code return from the method right away. So it doesn't get to updating your text.
And since the debugs are in different method, they are printed to the console correctly.
If something goes wrong, always suspect errors in console first.
And fix them before moving on to other solutions
I would add a log inside of AddScare that checks if HealthScript is null. That way, before the counter is logged, you check if it's null or not . . .
What i did was instead of saying tag i put it in as a public gameObject and it worked
ill remember that
That's the better option. Using Find methods aren't the best and it could've been misspelled . . .
Hello. I was experimenting with using UnityEvents instead of writing all listener code myself. I noticed a exceptional high delay in reloadig/re-compiling game ( when i save changes or press play). Is it in my head only, or was it due to unity events ? I have 18 listeners for 18 game obejcts attaching themselves.
i wouldn't know generally.. but you could always use the profiler and see how long the scripts taking
vs w/e you had before
ok so I have this code that is supposed to play an animation when the gameobject hits a y-cord of at most -1.2f and stays there for 3/4 of a second. The debug code shows that the entire script works, timer and everything, and the animation trigger gets set. But the animation doesn't play. Is there a problem with my animation trigger or something?
Show us...
it exceeds my character limit...
whats all this noise?
ill send a ss of the code
its the diff
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
Do not send ss
but not sure how/why it got enabled
or what its doing..
wait... is this hooked up to my repo?
soo... these gonna stick around until i commit?
no
maybe i send a link or sum?
Use Scriptbin to share your code with others quickly and easily.
there you go
oh
you said the trigger/param gets modified
soo does ur Condition of the transition have the same?
well can someone help me with this code its supposed to play an animation when it stays at a y coordinate of -1.2f or less for 3/4 of a second. The debug logs say that everythings working, the timer is starting and the animation trigger is being set, but for some reason the animation just doesn't play, is there something wrong with my triggers?
Code for reference: https://scriptbin.xyz/genawenugu.cs
Use Scriptbin to share your code with others quickly and easily.
That was the whole point yes
i figured it out dont worry
It's weird that you're resetting the trigger each frame
Anyway once the trigger is set it's up to your animator
if you'll select the gameobject during runtime you'll be able to see where and how the transition/animation is fuggered up, just there in the animator window #💻┃code-beginner message
just a tip
For something like these re-usable timer functions, is an interface a bad choice over something like an override function?
public interface ITimer
{
public bool BasicTimer(...) {...}
}
(Just in your opinion)
alright so I'm trying to figure out how to connect the animation trigger in my scrip tto the animation trigger in my animator so that when the gameobject hits a y coordinate of -1.2f or less, it plays an animation.
Here's the code: https://scriptbin.xyz/genawenugu.cs
Use Scriptbin to share your code with others quickly and easily.
I would use delegates for this rather than either interfaces or inheritance
Yeah I’ve never really used delegates or C# events or whatever, I guess it’s finally time
Show your animator, did you set up the arrow things correctly?
you want a ss?
Do you get the log that the animation trigger is set
yes
Then the problem is not the script
it might be the animator controller
when i look at the animator controller during the entire thing it goes through all the states like so but the animation still doesnt play
Look at the animator controller while the game is running. It should show you what state you are in
well if the animator works correctly is it the animation clip itself?
all of the states are going as so
it starts with entry going to placeholder empty state
then when the y-cord is met it does the transition to the play animation state
are my arrows messed up maybe?
no its not the animation clip
im looking at the preview and the gameobject just isnt moving could that have something to do with it?
Then it is completely working
is there something wrong with one of the transitions or states in the controller?
Does your animation state actually have a clip set
yes
If it's entering the state when you want it to, and it's staying there, the code is working, the transition is working, and it's in that state
yes
its giving the "The referenced script (Unknown) on this Behaviour is missing!" message but that would be a script problem which it isnt
Seems like it's all working. My guess is the clip isn't correct. Are you sure this animation clip actually animates anything
yes
if you look at it in inspector it plays the animation
but the preview in the transition doesnt show any movement on the objec
Make that animation state the entry state. Does it do the animation you want on startup
no
so it must not actually animate anything
Then the issue is the clip and this has nothing to do with the code
yes
but i have it set to the same object that is being animated in the motion field of the state
do you want an ss of the animation state?
@polar acorn Im so fr I can't find anything wrong with the clip
The referenced script on this Behaviour (Game Object 'Cylinder.001') is missing!
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
this is the message im getting
damn looks like my help vanished
RIP
I deletd all changes, it became faster again. doesnt prove anything, but something i did whie utilizing unit events was wrong
something on Cylinder.001 is missing
- use the Hierarchy and Inspector to scope out the issue
🤔 Interesting, I searched about that and seems you are right, deltas are not very accurate at WebGL
I just used them naively in two games and saw no issues whatsoever, quick search only gave me themes where one have weird game timers behavior when game is not focused, and the other had weird physics right after the game is loaded; I seemed to bypass that because I always have tiny extra loading bar and not allowing to play unfocused.
How do you check if the raycast hits anything?
the ray works, and the hit does get filled (the selector shit is also correct)
This returns true if the ray hit a collider. Otherwise, false . . .
If false, then set the color to normal . . .
Oh yeah my bad I forgot to put it outside the raycast itself
Sorry havent slept in over 12 hours
Thanks
Also, you can—and should—use a LayerMask to filter your objects. If your IHittable objects are on certain layers, select those layers for the layer mask. This will ensure the objects hit have an IHittable interface . . .
Yeah
could someone explain this in more detail? ive never heard this mentioned before
still need to look into this myself, but im pretty sure its referring to garbage collection
you cache the string so you dont hardcode it every use, every string live on its own in memory, so when you hardcode it you will get multiple representations of the same string in memory
its an object so its preferable to cache it instead creating it every use
Presumably, they're worried about the string being allocated on the heap when the class is instantiated.
Making it const would make it a only be allocated once per program start. That being said, using the text directly in GetAxis should have the same effect.
Strings that are just specified in code are interned and the same string declared somewhere else in code is shared
Only strings that are constructed dynamically will allocate
Yeah, so there's not much point in this "optimization".
The optimisation in the code above is bullshit, yes
Aside from maybe making it easy to access and modify during development.
well using a const for it is better but there is no perf or build size benefit
I don't really think a const is any better unless it's used elsewhere
Reminds me of a purchased package I had to deal with where this person SHARED 1 single int for all for loops
"better"
looks inside
no benefits
or maybe the person who wrote that code has backing in other language where CLR doesnt optimize string allocation
eh probably not, it takes time to learn properly what things matter and what doesn't
what's the use of Vector2 direction in CircleCast?
is it a capsule then ?
Hey i have a weird problem. I have a character shooting a projectile with a rigidbody and capsulecollider. the projectile is bouncing off an object with a boxcollider but in my OnCollisionEnter, nothing gets triggered, not even the Debug.Log at the beginning.
in a way, yes. the path it checks is a capsule. its basically just a thicker raycast. this might help to visualise it a bit more
can you send the !code?
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
A tool for sharing your source code with the world!
aswell as the colliders
is the OnCollisionEnter supposed to be on the Crossbow?
in most cases, you would put it on the projectile object
i thought because the crossbow generates the projectile`?
oh, that's the issue then. OnCollisionEnter will only detect collisions for the object it is placed on
so i should add another script for the bolt itself?
OnCollisionEnter is called when this collider/rigidbody has begun touching another rigidbody/collider.
fair enough.
worth noting in some situations that wording can get abit weird because iirc in some cases rigidbodys can recieve callbacks on behalf of objects parented under them or something like that. don't think it's relevant here but it can trip people up sometimes
oh right, yeah that's true.
my script crashed on this tho
Rigidbody boltRb = currentBolt.GetComponent<Rigidbody>();
whats the error?
nullreference
the bolt either doesn't have a rigidbody on it or currentBolt has not been assigned
the prefab has a rigidbody
A tool for sharing your source code with the world!
thats my boltcollision script
not jordan's response is objectively the answer you are looking for, code can't help change that
if that code is throwing an NRE it's either one of those two options
well, how do i assign currentBolt would be my question 😮
you likely just need to replace currentBolt with gameObject
sometimes i want to give back my degree and start sweeping hallways...
of course my bolt knows it is currentbolt 🤦♂️
thanks! its working now
mmh a little addon question. Why does it bounce off rigidbody but sticks in colliders?
ok i am in developer hell. i removed the rigidbody off a box standing in the scene and now my bolts dont fly anymore
what kind of joke is this
not entirely sure myself, probably a question for #⚛️┃physics
mmmh gonna head over there. but the part about not flying at all is really weird
the box isn't even linked to the bolt in any way shape or form
coconut moment
absolutely like this
||The file exists, but removing it does not affect the game||
wow who knew removing an asset that is used would cause problems 🤔
and its probably not a jpg but vtf
ah that makes sense, sounds like good practice
actually its optimised by CLR, so caching string is pointless for C#
I un-coconutted it!
you can intern strings at runtime it seems but otherwise string literals have this done at compile time https://learn.microsoft.com/en-us/dotnet/fundamentals/runtime-libraries/system-string-intern
still clean to do so though right?
especially if you're using that string in many places
yes, its always good to cache it for easy acces/change, but from optimization point of view is pointless
the point of using a constant is so you change it in 1 place vs many. Its not a "shared variable" when compiled though so talking about optimisation is meaningless
so lets stop
i was following youtube tutorial for basic 3d fps game, got to a point where to do gravity for the player so that he falls when not grounded, when playtesting, the player starts going in the air, how to fix?
I want to bring up that using int.ToString() is way worse than creating let's say 1000 strings in memory from 0 to 999 and then doing myStringArray[int]
form a garbage generating perspective
your gravity is positive and you are adding it rather than subtracting. either subtract gravity or make it negative
in other words - copy the tutorial correctly!
You are adding a positive gravity to the y axis of the playerVelocity . . .
sry, wait bad screenshot, i was trying to fix it because i thought that the negative value was what made it float
Negative means minus, right? Wouldn't that go down, not up?
makes sense, i was not reasonable, sorry
you need to fix that in the inspector
changing it there won't affect anything now that it's been serialized
i only have experienece in css and html, never did game development
what does that mean?
where can i do this?
it means open your unity editor
click on your object with the script on it
look at the inspector
and change the gravity value there
oh this, i already done that, its - in the inspector
you should probably go through !learn to learn the basics
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Also, for some reason you are assigning gravity to Time.deltaTime, then adding gravity to playerVelocity.y. That cannot be correct . . .
OHH
thanks that probably is it
yes, that was it
thank you very much, does anyone know some good video tutorials for begginners with some explanation as to what does what? the only tutorials ive found are made in a way where guy writes stuff with no explanation and im left to just copy his code
-offtopic- if i were to do a just a walking videogame with cool building to explore, should the building be done with all the shapes etc availible or is there some other more proper way?
should the building be done with all the shapes etc availible
what does that mean
I think he is asking whether it’s feasible to make his game idea entirely using engine shape primitives
To which the answer is: the better you want it to look, the more the answer becomes “no”
if i would want to recreate a real life building to be walkable ingame, what would be the best way to do it?
model it manually in blender or use one of those 3D-building scanner companies ($$$)
oh alright, ill try in blender then
wait, i have the 3d building scan availible
it would need some polishing maybe
in theory, if the random number rolls the same number twice here, what happens? does it make 2 with the same name, and windows then gives it a "(1)" in the name?
fromt his code? Nothin, you just have the same path
what happens depends entirely on what you are doing with that string. i would assume you're just writing to the file so it would overwrite the existing one
you have to show us what you're doing with that
No os will do what you suggest 😆
It will probably just override the file or fail as it already exists.
Ill be nice. You could do Random.Range(int.MinValue, int.MaxValue) but its better to try to use the time (e.g.DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()) combined with some other num to avoid saving duplicates.
oh okay thats good to know, should put in a check then
So I made it so when your grounded your drag remains the same and when your not grounded your drag decreases so the player can jump. I tried it out and it works but when I jump the player moves incredibly fast how can I fix that?
Watch "PlayerController - SampleScene - Windows, Mac, Linux - Unity 2022.3.26f1_ DX11 2025-02-28 15-30-00" on Streamable.
is that basically using system time to generate a random number?
i had the same problem, this didnt work
using UnityEngine;
public class MovementScript : MonoBehaviour
{
public CharacterController controller;
public float speed = 15f;
public float gravity = -9.81f;
Vector3 velocity;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
you can use the time in other ways such as DateTime.Now.ToString("YYYYMMDD_HHmmss")
im following the exact tutorial 😭
show what gravity is set to in the inspector
sigh my bad
if you want something that is unique you could use a GUID instead
Its certainly not random if we use the current datetime as a number/string but we know its always moving forward and its often better to have in files like this
@rancid tinsel
DateTime.Now.ToString("YYYYMMDD_HHmmss") is good as it will sort ascending by time for us 🙂 (format string may be wrong)
oh i actually did try DateTime.Now earlier but the string was slashes so i couldnt use it
didnt know you can format it like that, thanks!
Id prefer foobar_20250228_161401.txt instead of foobar_3i20483028472034802.txt
yeah i agree
btw, remember to put ```cs at the top. and not just ```
so with this i essentially drastically shrink the possibility of duplicates right?
its super overkill for what im doing but id like to learn best practice anyway
why not just use a GUID
1 D too many whoops
Do you intend to have multiple of these being made a second?
Guid.NewGuid().ToString()
oh yeah that could be a good idea too actually
like Rob said though, its easier to identify like this
I think combining both is sort of "best of both worlds" though
Instead of just adding a random number, you could just... check if a file exists before writing and append a (1) to it if it does
that gets dicey because what if the (1) already exists!
Like, if you really don't want to use GUIDs and you're creating multiple in a second
Same thing most programs do. (1) (1)
either way you need a while loop then
oh no im not disagreeing with using GUIDs
i meant that ill actually use a guid instead of random.range there, and that way i can still see them by the dates
like this
wait i got rid of the date 😭
my brain
like this sorry
without one of the Ds ofc
date is not guaranteed to be unique either but how big of an issue depends on if you have seconds or milli seconds in it
and ofc a users date can change
err you put the guid inside the date time to string()
thanks for spotting that
I made it so you can adjust the movement speed when your in the air. just need feed back on my script > https://paste.ofcode.org/jcstX4tk2tcUtMS7qC6Ugs
Guys why does waitforseconds work at the beginning of the game and not everytime. It supposed to wait 2.5 secs or?
And when i put waitforseconds line under the rotation code, it doesnt even wait at the beginning of the game, why?
The Code Is:
void Update()
{
if (Input.GetKeyDown(flashKey))
{
ToggleFlashlight();
}
StartCoroutine(FollowCamera());
}
IEnumerator FollowCamera()
{
yield return new WaitForSeconds(2.5f);
Flashlight.transform.rotation = Camera.main.transform.rotation;
}
Hey look it's that thing we told you would happen yesterday and you said it definitely wouldn't.
Here's what this code is doing:
Every frame, it starts a timer that waits 2.5 seconds.
Once that timer is done, it sets the Flashlight's rotation to whatever the camera's rotation currently is.
Then, next frame, the next timer you set is done, so that one sets the flashlight's rotation to the camera's.
Then, next frame, the next next timer you set is done, so that one sets the flashlight's rotation to the camera's.
Then, next frame, ...
oh
End result: You've made a system where the first 2.5 seconds of the game have no camera following, then it's as if you put it in update
btw why doesnt it wait when i put the waitforseconds line under the rotation code line
Because what is it waiting for
it sets the rotation, waits 2.5 seconds, does nothing, and ends
oh yeah u are right
You'd be telling it to rotate first, then wait. That's backwards . . .
do i use this channel for stuff about assets and how to add code to them
try asking question first?
I don't know, is your question related to beginner coding concepts in Unity?
i downloaded this asset pack and i don't know which script is supposed to be for the movement and jump animations and i want to know how to apply it onto the character with my script
That seems like something you'll need to check the documentation for that asset to determine
im guessing this is the code for it right?
You should probably look at the documentation it came with
by that do you mean the read me thing or am i supposed to look for something else
ReadMe is a good start yes.
it didn't have anything related to that
configure your !ide too
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
• :question: Other/None
sounds like a pretty garbage asset then
certainly there is a pdf or something there?
also nobody knows what code you're talking about (nor do i think anyone wants to go through it). if you have problems with an asset, contact the person who made it
could see that from the code lol
