#💻┃code-beginner
1 messages · Page 326 of 1
yep forgot the name
hi can someone help me with this script and tell me what am I doing wrong
right mouse click the error -> suggested fixes
to start with you dont seem to know the difference between upper and lower case
gotta fix those top two compile errors
The important bits of the errors are cut off
so why would expect a Unity Editor API to be available in a build?
you are referening an Editor only namespace, that does not exist in a build
where do i post questions about lightning
You cannot use anything from any UnityEditor namespace in a build
You probably added a using directive by accident.
Your IDE can auto-insert them based on the types you're trying to use
Now it looks like this and it says that ,,Random" dont have definition of ,,Range"
Yes, because System.Random is probably not the Random you actually wanted.
System's Random doesn't have a function named Range
You've been given the info to fix it
Hello, im new in unity and was just wondering how games like sims 4 handle pause when in build mode? I see that it doesnt entirely pause the game since it still lets me move and place objects/furniturr on screen
Everything that's not supposed to happen when the game is paused checks if the game is paused before it does that thing
"Pausing" is a pretty vague concept
You aren't completely freezing the game
(that would be useless; you couldn't unpause!)
If everything respects the current timescale correctly (so, nothing cares about the exact frame count or framerate), setting the timescale to zero will pause your game world
But you can still make parts of your game not respect the timescale
My menus all use Time.unscaledDeltaTime
as does the spectator mode, which means you can fly around even when the game is paused
Oh i see so i just have to set timescale to 0 and manually specify the parts that should not respect the timescale and use unscaleddeltatime. Thank you guys!
how do i return all GOs with a set tag ("mass"), except the GO thats running the script?
how can i reach the SkinnedMeshRenderer material's emissive property?
Ask your players to install a debugger in order to unpause
true
There isn't going to be a method that excludes the current game object, but you can filter the results.
It depends on the shader. You'll need to see what they've named that player. Then you'd use SetFloat or SetTexture2D or whatever type it is with that name.
https://docs.unity3d.com/ScriptReference/Material.html
i mean i may asked a wrong way, the skinnedmesh renderer using a material and the material has this emission_power property
So, you'd need to find out what that property is named internally in the shader and use one of the Set___ functions on material to set it
and how do i track it down? my current alternative solution is: having 2 materials (one with 0 and one with 1 emission) and changing the skinnedmeshrenderer's material.
If you look at the shader asset in the inspector it should have the names of everything.
this thing?
Yes. Looks like the internal name for Emission_Power is Vector1_34B15A85 if I'm reading that right
So that'd be the string you'd use to set that float
I'm making a menu animation. First i set it's Y size to 0 so it isnt visible:
rect.localScale = new Vector2(rect.localScale.x, 0f);```
then i call an OpeningAnim() method so it will scale up the Y value, creating a cool animation as if the UI "jumps" out:
```cs
public void OpeningAnim()
{
rect.DOScale(new Vector2(rect.localScale.x, 1f), duration).SetEase(Ease.OutBack);
}```
The problem i have is that the Title, Play and Exit text objects (those are TextMeshPro objects) dissapear after calling OpeningAnim. It also happens when i set the scale normally (`rect.localScale = new Vector2(rect.localScale.x, 1f);`), not via DOTween's DOScale (`rect.DOScale(new Vector2(rect.localScale.x, 1f), duration).SetEase(Ease.OutBack);`). the only objects that are still visible are images.
Note that I scale the whole Canvas object.
I also provide these screenshots with my hierarchy objects, how the menu is supposed to look and how it should not.
Which object is rect referring to?
this doesnt happen when i set the canva's Y local scale to 0, and then back to 1
the Rect Transform in the Canvas
i want it to go from scaleY 0 to scaleY 1
that's a code answer
I want to know what effect you're trying to achieve
visually
Do you want things to stretch or do you want things to... be slowly revealed as if being uncovered by something?>
i want it to suddenly stretch
the animation is done right, i tested it and the images are animated properly. the only issue is that the Text objects (game title etc) dissapear for some reason.
It works, thanks. Super complicated tho on the first blink and changing material seems easier but i don't want to clutter my project so i will get used to it.
It'd be easier if whoever made the shader gave that property a sensible name
I believe I have run into this issue before. Try calling ForceMeshUpdate on the text mesh pro objects
i never had this problem, but if i try to declare a Vector3 i have to declare it UnityEnginge.Vector3 to work, what can i do?
Put using UnityEngine; at the top of your script
it is there
Show your code and the errors you're getting. You did something wrong
Or is it because you have an ambiguous declaration from another lib ?
probably that
you probably have using System.Numerics;
But yeah sharing the error message will reveal everything
If the other lib is needed you can set an alias using Vector3= UnityEngine.Vector3 at the top
thanks
could someone help me out troubleshoot/debug/fix a score system im trying to implement in a flappy bird like game?
Hi, I would like to take for example a number 1 and increase it to number 10 in 2seconds how would I be able to achieve that? (yes I do know its a silly question)
I want to do this for a smooth transition between FOV changes
If you have a specific question, just ask it, with details and context.
Use either Update or a Coroutine. It can be done with e.g. Mathf.MoveTowards
DOtWeen is a good option too
hmm I see since I dont understand Coroutines will check out the Mathf solution THX a lot
those are not mutually exclusive things
doesn't really work:
private void UpdateTextMeshes()
{
foreach (var text in texts)
{
text.ForceMeshUpdate();
Debug.Log("Updated");
}
}```
i call it in start(), is it done right?:
```cs
texts = FindObjectsOfType<TextMeshProUGUI>();
InvokeRepeating(nameof(UpdateTextMeshes), 1f, 1f);
for fov change it would be very simple. Something like:
float zoomFov = 40;
float normalFov = 90;
float targetFov;
float currentFov;
float fovChangeSpeed = 100f;
Camera myCam; // make sure to assign this
void Start() {
currentFov = normalFov;
}
void Update() {
currentFov = Mathf.MoveTowards(currentFov, targetFov, fovChangeSpeed * Time.deltaTime);
myCam.fov = currentFov;
}
void Zoom() {
targetFov = zoomFov;
}
void UnZoom() {
targetFov = normalFov;
}```
uuuh ok THX
You should be calling it every time the animation updates, I believe DoTween has a callback for that. However doing it like this should at least show the text now right ?
it doesn't, it is as if i didn't add this TextMeshPro mesh update:
i will try to do the DoTween callback if it exists
one way or another, it still should update the text's mesh.
That's wrong.
The ForceMeshUpdate method should be called just before performing any calculations, which may require the updated info of the text.
Calling it every 1 second is blind-guessing
mb, so basically I made this game object that just has a box collider set on isTrigger and added an AddScore script so that whenever the player collides with the box it just increases the score value then I asign the text object a script that updates the score based on the previous script. Issue is that I m getting this error
That's just a NullReferenceException
it's the same as any other NullReferenceException
what does that mean?
If you, say, perform any calculations in the OnValidate method, you should call the ForceMeshUpdate method just before accessing the text's variables
private void OnValidate()
{
text.ForceMeshUpdate();
// calculate stuff
}
It's the most common error for beginners to deal with and it's extremely simple
cuz the score isnt updating
perfect lol
Yeah because you haven't referenced something properly
you're trying to use a reference that is not assigned
look at the filename and line number in your error
it tells you exactly where to look
Score.cs line 16
You don't have a UnityEngine.UI.Text component attached to the same GameObject as this script
simple
yes
Imagine having a red apple in your room and trying to eat it. But you cannot eat it, because it doesn't exist. It is null and gets an error.
look at your inspector
No Text there
So the GetComponent returns null.
what do i put in // calculate stuff ? i don't do any changes on the TextMeshProUGUI objects, i don't change their text etc.
calculate*, that was a typo
sry I still dont get it
Do you see a Text component here anywhere?
I don't
So the code won't find one
because it doesn't exist
I haven't seen the full context, I have just seen you using ForceMeshUpdate and said you weren't using it correctly.
You don't need to use this method unless you access any variables of your text, which are updated when the Mesh is changed. It is changed in the Update method.
ok, thank you
So why did you show a screenshot of the AddScore object?
yea idk mb
expand that Text thing
I believe Uri suggested you to use ForceMeshUpdate here, but I don't think this is an issue.
Are you having the same issue we've discussed earlier, with the UI not being displayed on runtime?
The problem is on GameManagerState but i cant really understand the problem i would be glad if someone can help
m getting an error on GameManager.GetComponent<GameManager>().SetGameManagerState(GameManager.GameManagerState.GameOver); at the first block of code
You should share the error. WE're not mind readers
"an error" is too vague
You probably just have another copy of this script in the scene where there is no Text component
Please, consider sharing the error. You're probably getting a NullReferenceException
oh yea true! Found it, now I dont have any more errors but the score its still not updating
You probably jsut dont' have any code changing the score
¯_(ツ)_/¯
Also, I don't see why you're trying the access the GameManager component from the variable, called GameManager.
Are you, perhaps, willing to change its type?
is it possible to crash in untity because of simply clicking a button
Error was in my language so its my bad not to share , its CS1061 it says "gameobject" does not contain a "GameManagerState" definition, and no accessible "GameManagerState" extension method was found that accepts a first argument of Type "GameObject". (maybe you are missing a usage directive or assembly reference?)
Yes
depends what the button does
I have this code on the gameobject that is parented with the two pipes
and have the box collider to isTrigger
Calls a while (true), probably
which function does the button call
atleast for a beginner like me :/
Also that's not a very big script
the button sets iscrouching to true which then calls the crouchtransition function
while (Mathf.Abs(heightDiff) > 0.01f)
{
elapsedTime += Time.deltaTime;
float lerpValue = Mathf.Lerp(0.0f, 1.0f, elapsedTime * crouchSpeed);
cameraTransform.localPosition = new Vector3(cameraTransform.localPosition.x, currentHeight + (lerpValue * heightDiff), cameraTransform.localPosition.z);
}```
this code is pretty explicitly an infinite loop
nothing inside the while loop changes heightDiff
so if that condition is true at the start, it will be true forever
Because you're trying to access the GameManagerState variable from the GameManager, which type is GameObject. See, that's why I was referring to your names being slightly bad.
This also looks like something that is supposed to be in a coroutine @warm geode
you would need frames to elapse between each loop for this to make sense
hey!
private void OnTriggerEnter2D(Collider2D collision)
{
if((collision.tag=="EnemyShipTag")|| (collision.tag == "EnemyBulletTag"))
{
PlayExplosion();
lives--;
TextLives.text = lives.ToString();
if(lives == 0)
{
GameManager.GetComponent<GameManager>().SetGameManagerState(GameManager.GameManagerState.GameOver);
gameObject.SetActive(false);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public GameObject playButton;
public GameObject playerShip;
public enum GameManagerState
{
Opening,
Gameplay,
GameOver
}
GameManagerState GMState;
void Start()
{
GMStat e= GameManagerState.Opening;
}
// Update is called once per frame
void UpdateGameManagerState()
{
switch(GMState)
{
case GameManagerState.Opening:
break;
case GameManagerState.Gameplay:
break;
case GameManagerState.GameOver:
break;
}
}
public void SetGameManagerState(GameManagerState state)
{
GMState = state;
UpdateGameManagerState ();
}
}
im getting an error on GameManager.GetComponent<GameManager>().SetGameManagerState(GameManager.GameManagerState.GameOver); at the first block of code. why is that happening ? couldnt solve the problem
CS1061 it says "gameobject" does not contain a "GameManagerState" definition, and no accessible "GameManagerState" extension method was found that accepts a first argument of Type "GameObject". (maybe you are missing a usage directive or assembly reference?)
Now, I am trying to make a fps character controller. I am using the new input system and the controls are so jittery. I look on google and changed the update mode to dynamic update and at the beginning (when i have only camera look script) it was fine. But when i add the movement script, it broke and begin jittery again (both movement and camera). Here is my simple movement code:
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public InputManager inputManager; // Refence to our InputManager component
public CharacterController controller; // Reference to your CharacterController component[SerializeField] private float smoothInputSpeed = .2f; public float playerSpeed; private Vector2 currentInputVector; private Vector2 smoothInputVelocity; private void Update() { Vector2 input = inputManager.inputMaster.Player.Move.ReadValue<Vector2>(); currentInputVector = Vector2.SmoothDamp(currentInputVector, input, ref smoothInputVelocity, smoothInputSpeed); Quaternion characterRotation = transform.rotation; Vector3 move = characterRotation * new Vector3(currentInputVector.x, 0, currentInputVector.y); controller.Move(move * Time.deltaTime * playerSpeed); }}
people are already answering you - why did you just repost the question
Have you, perhaps, found my answer not good enough?
i did use couroutine at first but the i scrapped it to use functions instead, but thanks for the help i try again with couroutines and not make infinite loops
i was trying to gather the things up cuz my asking style was bad
no its not about that
Why not edit the original question?
It's more likely related to the code that moves your camera and or rotates your character
A coroutine is a function
deleted the original one bro instead of i cleared the question sorry
You have no reason to gather the things up, because I've already provided you with the answer, which is enough for you to fully fix your issue
{
float mouseX = inputManager.inputMaster.Player.MouseX.ReadValue<float>() * sensitivity * Time.deltaTime;
float mouseY = inputManager.inputMaster.Player.MouseY.ReadValue<float>() * sensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}```
Can you take a look at it?
you should not be multiplying mouse input byTime.deltaTime
that's a classic mistake
yeah thank you for answer bro im trying to understand now . can you be clear a bit i would be glad for that
(make sure to adjust your sensitivity down as well to compensate)
What exactly do you find hard to understand in the answer provided?
Ohhh thank you so much i will delete and try again
its not so much i tried 5f, 7f and 25f
But now its so, so fast
You simply don't need to apply the Time.deltaTime, as it's already calculated in in that InputAction.
Also consider making a Vector2 mouseInput instead of those 2 floats
As i said you have to reduce the sensitivity after removing deltaTime
Like this?
Oh okay I revert it
revert what???
This to old one
this looks correct
what did you have before?
pass through?
it should be Vector2
I would have expected that you had it as a Vector2 before 😬
well wait
I mean
I guess it can work either way
this is definitely better though
you can do this then:
Vector2 mouseInput = inputMaster.Player.Mouse.ReadValue<Vector2>();```
and get mouseInput.y and mouseInput.x
I think like this too but I switched up from unreal and I cant resolve how can I implement it
Tysm!!
sorry i am asking too much but how can i get the x and y value?
mouseInput.x / mouseInput.y
That's the basics
Vector2 is a struct, which has x and y variables
I just explained
This is how you access them
sorry i didnt saw it
Why we are using mouseInput instead of directly Mouse.X / Mouse.Y?
There is no Mouse.X
we use the thing that we have
Sorry i forget about we are using a different name for the variable
How can I get a game object from a different scene? Like I have the player and I have the main menu and have save and load system game object in both scenes which have the Save and load system script which has a public game object player parent which I just drag and drop the player but in the main menu I don't have the player ofc so I'm not sure how can I grab the player from the other scene
Perhaps you mean float mouseX and float mouseY? Because it makes much more sense to store 2 floats, which are named after the axes, in a Vector2
Read it but still not sure how I can do it 
No i mean, when i named the input "Mouse" in the engine, i forget about we give a different variable name in the code and tried directly using it
mouseInput makes more sense than mouse, as this is... the input from the mouse
Yep i agree with it
EditorSceneManager.preventCrossSceneReferences could perhaps be this?
you skimmed it and not read it then
I did read it tho
so which part you don't understand
It literally says that is undesirable
Are both your scenes loaded at the same time?
How could I do one of those options
Nope , I only load the scene where the player is when I press play
having an issue with spine IK where im trying to get the torso/spine bone of the character to face towards the target in a somewhat realistic manner, and i cant find any good guides on spine IK anywhere
https://gdl.space/uradaquton.cs - (the first bit is just head ik)
Why do you need the player in the main menu scene?
Then you cannot get the player from the other scene. Change your architecture
I just need a reference to it since I'm getting the components on that player like inventory , shotting script n etc
Consider DDOL for data. Probably not the whole actual player
Looks fine to me
Why do you need these references in the main menu?
DDOL?
DontDestroyOnLoad
Cause I need it for the save and load script?
Pretty sure we've talked about it before?
Why?
I did suggest you this last time
Oh yeah
you just kinda ignored it
Please elaborate. Very likely you're needing to decouple data/responsibility.
were you being fr?
is there a collider type that is best for a player character
In regards to? This is the coding channel btw. For non-coding questions, try asking in #💻┃unity-talk
For sure. Your character looks amazing.
is putting a static collider on the player fine? or can it not have it because its a moving object
You'd put a static collider on non moving objects.
For more info https://docs.unity3d.com/Manual/CollidersOverview.html
Consider changing the LookRotation's 2nd parameter. It is set to Vector3.up by default, you may reverse it to -Vector3.up. This should change the direction the spine is rotated in.
Even though, as I have previously mentioned, your character already looks amazing and their posture doesn't require any changes.
If I could ask , can you maybe send something to learn for that or a tutorial or smth cause I never used DDOL for data
DDOLs are usually used with singletons or simply applied in the Awake
private void Awake()
{
DontDestroyOnLoad(gameObject);
}
i think it may not be the problem with text, but rather with the canvas? i deleted and recreated the Title text while in Play Mode, and the issue still persists
For singletons, I would recommend you this tutorial. I like to use the generic one.
The save/load script is likely doing too much. The player from the next scene should instead be responsible for acquiring it's data from your loading script/manager rather than the script/manager trying to configure the player object from the next scene before it's loaded - assuming that's the reason why a reference of the player is needed.
i feel like the text is still there tho, its in the Hierarchy window and it's interactable (when i press the area slightly below the white line, where the Play button should be located, it switched to the Game scene)
https://unity.huh.how/references
This goes over it a little in the singleton section (which is what I am recommending).
Capture the data you need and pass it via the singleton.
May I ask(sorry to ask so many questions) but wdym capture the data and pass it via the singleton?
how can i make scriptable objects with custom method or ability for each? can i make an interface abstract and edit the code somehow of an object?
Well I don't know. You haven't been super clear on what you need.
You mentioned an inventory, so maybe the inventory...
As Dalphat said though, this may just be a bad architecture with the save/load script doing too much.
You just add a method to the code for your scriptable objects. You can make it abstract and child classes can implement logic in the same way as regular classes
if i create the object in the assets then, how do i customize the method?
hey! is there a way to play an animation reversed like set the speed to -1 via code?
By creating a child class which implements the method however it wants.
oh a child scriptable object?
will it begin to overly fill my create asset menu by doing so?
https://docs.unity3d.com/ScriptReference/AnimatorStateInfo-speedMultiplier.html you can by making a float paramter and using that as the speed multiplier for the state in the controller
You can use folders in asset menu
With a "/"
setting it to -Vector3.back worked slightly but now hes just off to one side
Show the orientation of the spine bone. Select it and make sure you have gizmos in local mode
thanks 🙂
@lost anvil Oh you are setting the bone's local rotation, I suppose that's the issue? Since you are calculating the direction in world space, not local
Could you just set its world rotation (transform.rotation) instead? I never used OnAnimatorIK, just LateUpdate, so I dont know
https://paste.ofcode.org/35KkmSuca6kgapMBBBZrnzg (SaveAndLoadSystem script) not sure if im doing too much , it might be and i dont realize it, the playerParent is simply so i can drag and drop the player gameobject with has all the components i need like inventory and playerstats , the problem is , i dont have that said player gameobject in the main menu obv so when i want to press the continue button which loads the saved data it well doesnt work cause it cant find the player gameobject in the main menu scene when i press the continue button so ofc it doesnt load so i dont know how i can load the needed player data like current ammo or currentlyEquippedWeapon etc and gives me an error so im not sure how i can do it ngl.
Often a capsule or sphere is better since it doesn't have hard edges that can get stuck
is this possible in LateUpdate?
like the way i want
Yeah you can rotate bones in LateUpdate since it runs after animations
👍 ill try that
So you HAVE this savedata struct. Why get the player instead of just passing that struct into the next scene via DDOL singleton?
Considering you only need to LOAD from the main menu, not save
how can i pass that struct into the next scene?
Via a ddol singleton
public SaveData data;
i have it but how can i use it now? if i jsut wanna load the data (this is in the main menu manager script)
Just set saveData to the data you loaded?
You probably want your Load() method to actually RETURN the savedata struct. As it is, you load it and then throw it away without caching it
so smth like this? not sure if its right which i hope it is lmao (left is the mainmenuManager script and left is saveandloadSystem script)
No, not at all. Why would you pass savedata IN to the load function. I said return it FROM it
saveData = saveAndLoadSystem.Load();
I am trying to change the hue from 0 to 360, but it doesn't go through the other colors. What I'm doing wrong? I also want it to go cyclically.
private float time = 0.0f;
void Update()
{
time += Time.deltaTime;
material.color = Color.Lerp(
Color.HSVToRGB(0.0f, 1.0f, 1.0f),
Color.HSVToRGB(1.0f, 1.0f, 1.0f),
time
);
}
what does it do?
as for making it cyclical you can just do:
time += Time.deltaTime;
time %= 1;
material.color = Color.Lerp(
Color.HSVToRGB(0.0f, 1.0f, 1.0f),
Color.HSVToRGB(1.0f, 1.0f, 1.0f),
time
);```
The color stays being red instead of it going through orange, yellow, green etc.
void Start()
{
MeshRenderer renderer = GetComponent<MeshRenderer>();
material = renderer.materials[0];
}
you could just do material = renderer.material;
no need for the array
but yeah do you have any errors in your console?
did that but i prbly did smth stupid
You have to of course change the return signature of the method
And return it
I don't. I can lerp it from red (0.0f) to teal (0.5f), but not red (0.0f) to red (1.0f) through other hues.
well here's the thing
0 and 1 are the same hue actually
change the void to SaveData and then return saveData at the end of the method?
so maybe try this:
time += Time.deltaTime;
time %= 1;
material.color = Color.HSVtoRGB(time, 1, 1);``` @queen adder
because if you do the color lerping like that it's going to think it's lerping from Pure Red to Pure Red
In RGB it thinks it's lerping from (255, 0, 0) to (255, 0, 0) which won't do anything of course
how do I add animations to my player? like when I run I want a running animation. I got one from mixamo but dont know how
HAve you looked for stuff online?
https://www.youtube.com/watch?v=9H0aJhKSlEQ
https://www.youtube.com/watch?v=sgD-Z5sTK1Q
yes but I cant seem to find the right one I will take a look at the ones you have sent
Yep
okay good to know
okay so i got a small problem since im using playerParent to find the components i need like inventory n such and i set the playerParent to private , i tried many times to reference itbut i failed miserably
whats the problem?
Good lord just put a script on that parent object and directly reference those others in the inspector
You should really assign these in the inspector
good idea lmao
i really s ho u ld
I prefer to GetComponent if I am using requiredcomponent attribute
oh but for parent stuff yeah, just assign it imo
did all of that and it still uh doesnt work , gives me the errors in the vid when pressing the continue button
You mentioned errors, but the console is closed
What errors
There are no errors in this video
Also, having the savedata in the ddol singleton doesn't help if you don't actually pull that data and update the player with it
how can i pull it and update the player?
By getting the reference and updating variables from it?
getthe reference like this?
your switching scene, this code below wont run i dont think?
so why would that work
It's in DDOL.
It will but it'll run before the scene swaps
since that happens at end of frame
You don't actually DO anything with the savedata, so no
It's just some struct sitting there
also meant to show this vid mb
then how can i get the reference and then update the saveData variables to what? since i dont have the player
It's a singleton. The player does it itself in awake or start
There is a LOT you actually need to research to get this right.
I recommend checking out a c# course
https://www.w3schools.com/cs/index.php
Also read this on singletons again
https://unity.huh.how/references
yeah but how do i update variables from it and to what cause idk what
with the CreateAssetMenu can i organize all of the assets into a folder/dropdown of some sort
so it doesn't fill my create menu with a load of objects
yeah in the path name
can you give me an example
menuName its called
oh wait wha
[CreateAssetMenu("New Gun", "Gun/New Gun")] something like that i think?
try it and see
does not contain a constructor that takes 2 args
show what you did
nvm
@cinder crag It's super basic. Say savedata has an ammunition count.
player.AmmoCount = SaveData.AmmoCount
It's dot notation and an equals sign
I REALLY recommend a basic c# course
worked 👍
think i can do it lmao
is this IDE even configured?
do you see any red at all
no red at all
That would be a design question of when you should do it but relative to just acquiring the data, you'd have a script on the player in the new scene that would just load the necessary data from the save manager in Start or something. For example, if you're wanting to Update/load the player's position:cs private void Start() { transform.position = SaveData.Instance.playerPosition; }
ye it is
No. Not this at all
This is almost the opposite of what you want, except the player isn't involved so it isn't even close to being the opposite
First, you need to be doing all that code on a component on the player!
Then, you are pulling FROM savedata, not setting its values
OOOOH
thats all i needed honestly
something like this? and then put this on the player parent?
I mean I guess...
That is fine
i did something bad? 
i am happy with fine
thought if im putting on the player , i can just do that
sinc ethats where the rest of the components are
Prefer serialized references whenever possible
But that is taste
It is fine
Yes, better
well damn , i will use that then
Also, why not transform.position = saveData.playerPos
oops im dumb , mb mb
for some reason these errors appear when i saved and tried to laod in when pressing the continue button in main menu
So those references in the given scripts on the given line are null (not set). Someone was just going over what that means with you like yesterday
sent the wrong ss , these the errors appear when i have the save file and try to load in with the continue button
I mean. The response is the same
Those scripts on that line have some reference you are trying to access, and the reference is not set
line 66 is in the continue button method used for the on click event
saveAndLoadSystem is null
im not setting a reference to it cause i dont know how to ngl 😭
since its in another scene
well that wont work
That is the thing that has been supposed to be in ddol then
can try this
Is it on the same gameobject as this script?
I thought you said it was in a different scene
nope
Then no, that code will not work
it is on a empty gameobject
in that different scene
i'm kinda confused
basically i want to change the sprite for an tmp image but im not sure what function i need to use to set the source image
have you tried searching for how to change the sprite or source image?
tried setsprite
to be in ddol wdym?
doesnt work with an tmp image
I don't understand what the question is
like wdym by to be in the dont destroy on load?
never heard of an TMP image before . . .
I don't know how i can say it any simpler
Put it in ddol. So that you can access it
Don't destroy on load(DontDestroyOnLoad) is a function that make your gameobject don't destroy when you change your scene
We had been over that about 5 times over the last few days. They know what DontDestroyOnLoad is
But I appreciate it
its a ui image, not a tmp image
like this?
Terrible place to put it
I sent you that link like three times
ok nvm im stupid, .sprite just works
Don't NEED to, but that is the best place to. And you don't want to call the function over and over
specifed the wrong variable as well
yep . . .
placed it in start method but get this error when i get to the main menu
Show your line 24
It's the DontDestroyOnLoad method in the start method
so what is saveAndLoadSystem ?
So MainMenuManager is DDOL as well?
Hey guys i have a really random problem.
Im generating an Object with an Script. Im attaching a Mesh Collider onto it (with a script).
The Objects Mesh Collider doesnt work tho. But if im enabling convex is does. The problem is it doesnt work if i enable Convex by default. Changing the State (or interacting with options of the default filter) enable it
Uh no it isn't
Do I put the DontDestroyOnLoad in the save and load system script?
like DontDestroyOnLoad(gameobject);
The error clearly says it is in MainMenuManager
What is line 24 of MainMenuManager
he put the DontDestroyOnLoad in mainmenu ^^
Things seem really convoluted going back and forth with references
Oof
This is what I told you to do a long time ago. Why is MainMenuManager a DDOL, isn't it just for the main menu?
Save and load is what was recommended for ddol
i put the dontdestoryonload in the save and laod system script and the errors somehow still appear
These are different errors
Same error as this screen xD
Where did you reference the SaveAndLoadSystem in the MainMenuManager ?
at the start
Show the line or in the inspector
this is just where you declare it, have you not learned anything from yesterday?
mb , im tired its almsot 3 am
This seems like the exact same issue as yesterday. Declaration vs actually setting the reference
Then stop
dont wanna stop until i fix the problem doe
that means nothing, if i asked you at 3pm you would still not have a clue
Don't waste your time and ours by coding by approximation without fully even getting it
im a beginner , ofc i wouldnt
no, if you are beginner then you should know exactly what that is
this is one of the first things you learn
On the screen where is the error ? because its say on line 66
its line 67 but accidently pressed enter
the gameobject is on the scene and with the tag ?
its not on the main menu scene but idk how to grab it from the scene where its at
This convo brings up a question I have that may have a simple answer.
Initializing properties in code vs in the inspector.
At first glance it seems ambiguous, as in its user preference. But what is the standardized answer? I don’t recall the junior programming pathway addressing this.
Whatever is easier and your preference is the standard.
That is to say, it really doesn't matter.
Just that if you do it in code, do it in Awake.
it matters when unity decides to dereference your editor values :(
usually if it's supposed to be part of the same GO, i'd just use require component attribute with GetComponent
otherwise reference by editor
@frosty hound @timber tide gotchya, thanks guys.
The same GO? I’m not familiar with that acronym
Ah, Duh 😂
useful attribute
Cool, RequireComponent is a new one for me.
I grabbed this folder for Twitch Integration, it's got its own folder in the Assets folder, I haven't added it to my project's hierarchy proper. The scripts seem to just run on their own, which doesn't quite make sense to me since I thought I'd need them in the project proper, as a part of a gameObject, in order for them to do that. If I want to start my game w/o the scripts in this project enabled, how do I do that when it's not even in the hierarchy, yet seems to be getting run anyway?
Hi everyone, sorry, I came across this problem, when the enemy opens the doors, he often gets stuck in a corner like this, he keeps walking towards the wall/door, how could I overcome this problem?
make em half ghost so they can phase through the door and add that to the lore to disguise the real reasoning
more serious answer, fix the pathfinding obviously, or make the doors always open inward
make it a obstacle, recalculate the destination, ect
the idea is not masculine hahaha It remains the same if the doors are on the inside, it will still get stuck in the corners
Not masculine?
And mao meant inwards from the player (changing direction every time based on agent position). So there would never be the corner to be stuck in
Or just make the door an actual obstacle.
the structure is made of many anoles, it would still remain blocked
I try to make the door itself an obstacle, even if it would then cause problems to enter other rooms, since it would not calculate the pathfind from one room to another with an obstacle in the middle
Anoles? I don't know what that means. I think you are simply misunderstanding the suggestion.
Also, yes, you have to consider that case in pathfinding. Pathfinding is not easy.
Keep track of POSSIBLE paths and alter them when in range.
Or do partial paths one after another
Or make doors not obstacles, and only make them obstacles when opened
it could be a good idea
For my game I am trying to create a main menu. The main menu is simple and just has a play button. When the play button is pressed the screen is supposed to fade to black. The way the fade works is that there is a black screen image that is transparent within a camera render mode canvas. When the button is pressed the script slowly adds to the A value of the RGBA to that it decreases it's transparency. For some reason this isn't happening and my cursor isn't being highlighted when I'm hovering over the button as well. How would I fix these issues. Also here is the script for the button.
https://gdl.space/axucesoquv.cs
Can I call a method as an animation event and pass a parameter to it?
So.... yes it does, I would had swear that I tried before and didn't let me pass anything
https://hastebin.com/share/akuzaseziq.csharp how come after a few times of the player throwing the katana consecutively the next time they throw it will throw for like half a second and immediately return back
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you need to reset the returnForce
the returnForce variable is getting excessively high after each throw
returnForce += Time.deltaTime * 5; this keeps getting bigger and bigger.. each time u use it
you could just use = Time.deltaTime * 5;
not sure why you use += edit: if you want to use the += to simulate some kind of increase.. you still should reset the variable before each time you use it
i think, it's want an index
👍 hoorah!
PlayOneShot(music); is an alternative to assigning the clip and then playing
2 lines becomes 1 line
oh nice
btw im kinda worried about adding sfxs to my game
Also i think Play has a limitation of not being able to play multiple things but someone should confirm this. 
im not sure how it will work since (tower defence game) the towers can scale attack speed infinitely, and there will be multiple at once - how will that work with one audio source?
would it play multiple at once
or would it overwrite it
ive never done sound before
OneShot will play like 3 clips at once i believe..
i normally just stop it..
src.Stop();
src.PlayOneShot();
I thought it's unlimited.
can you add a source to every tower?
i could, but im trying to do it via a sound manager script
id just Stop(); and then Play();
i should probably somehow figure out a way to scale the sound effects length with attack speed tho?
It’s limited by the number of real and virtual voices. PlayOneShot essentially copies the audio source under the hood and plays the clip on the new source. If used many times in a frame there are performance considerations in using it.
i right understand, that you making one script for all sounds?
what happens if you exceed the 32 number? will it just start overwriting the previous one? as in stop the last one in the "queue" and play the new one?
Hey so this is my code provided "https://gdl.space/raw/keyunogune"
Descrp: Me and my partner tried fixing the issues with just errors for the past hour and how to add the navmesh surface component which I finally figured out. Partner left me to finish the project due tomorrow which is no problem. The issue I am currently having is the enemy is moving in a straight line ,slowly spinning, but not following me. I was hoping to find a solution to this with some help. Some troubleshooting I tried doing was increasing the obstacle radius , checking if any obstacles were blocking , did speed and acceleration but to no avail.I also did make sure to bake within the navmesh surface .
Currently no error messages.
yes basically, the script is a singleton that i can call from other scripts to play the relevant sounds
SoundManager.Instance.PlaySFX(soundEffect) basically
ok, so you can't make it as component, right?
not with that approach
AudioManagers are a common use-case for Singletons
i think your method would be fine or maybe even better
but it would take a lot more time i feel like
also fixing potential bugs would be annoying
Depends on the priority setting of the source that wants to play
im not sure what that is, is that how it would work on default?
Audio source has a priority setting by default its the same on all
https://docs.unity3d.com/ScriptReference/AudioSource.PlayClipAtPoint.html
you can use this to play the clip @ the location of each tower..
more elegant solution to running an audiosource on each tower
it would all be on 1 audio source
So no, if you exceed the 32 limit a new sound will not play since it will not have a higher priority
if ur playing more than 32 audio sources at a time imma uninstall the game anyway..
thats stimulus overload 🤣
This is a very limited approach. Are you sure you will not need different audio settings ?
as in, it would wait for the slot to free up and if its empty then play it?
It will simply not play
else if not empty, not play
It will go into the void never to be seen again
i dont think so, at least i hope i wont
im not going to go crazy with the sound effects
im just hoping the scaling nature of my game doesnt affect it too much
right, and then when there are 31 sounds playing after 1 has finished and a new one wants to be played, it will play?
not unless u have logic running to queue it up
Yes
ah, i thought he meant one he called previously when the 32 was full
By wants to play if you mean that you called Play somewhere in code then yes
There is no built in queue
The 32 limit can be changed from the settings
i just use an audiomanager.. if theres not enough sources it creates one.. plays the sound and then destroys itself..
i haven't implemented pooling yet.. but its on my To-do list
i think i might give Unity's pooling system a try too
i haven't used it yet.. and its been something ive been wondering about
So the way our sound system works is we have sound banks. Each sfx in a bank has it’s own audio source settings. When it’s time to play a sound the system grabs a source from a pool, applies the settings, places the source in the world(if it is spatialized) and plays it.
thats a good idea, im just trying to cut corners right now because im finished with first year of uni after i hand this in lmao
It also handles environmental sources by stopping them when they are far away from the player.
i dont even necessarily need to do it, but its like the last thing on my to-do list
ahh, thats clever
ya, for a simple manager..
source.Stop();
source.PlayOneShot();``` is my goto solution
It’s a bit more complicated than that since it also has an internal queue but that is the gist of it
im running into a bug because of a bit i changed just now
this bit always results in the if being true despite being on the other scene
which bit now?
if (main menu) bit
and when i go back to the main menu it says its on the other scene
maybe its to do with when the method is called
let me double check
I have code, that applies on all of the text & all of the objects on the desk```c#
figure.transform.localScale = new Vector3(size, size, size);
text.transform.SetParent(figure.transform);
text.transform.localPosition = new Vector3(0, size / 2, 0);
heck ya
how do i apply a force to a gameobject at an angle?
AddForce for example uses a Vector3 for the force.. force is applied along the direction of the Vector..
so you'd calculate the direction of ur angle and use that..
im so happy old me was lazy enough to make separate scripts for different projectiles
trigonometry has entered the chat
now I just had to add one line for the sound effects to each one lol
something like this ```cs
public float angleInDegrees = 90f; // starting angle in degrees
float angleInRadians = angleInDegrees * Mathf.Deg2Rad; // convert angle to radians
Vector3 forceDirection = new Vector3(Mathf.Cos(angleInRadians), Mathf.Sin(angleInRadians), 0f); //calculate the direction using some trig
rb.AddForce(forceDirection * forceMagnitude, ForceMode.Impulse);```
if the object has a initial rotation already you might wanna run it thru TransformDirection to get the proper direction
Vector3 forceDirection = transform.TransformDirection(new Vector3(Mathf.Cos(angleInRadians), Mathf.Sin(angleInRadians), 0f));
since I'm actually not good with trigonometry and the whole sin/cos stuff i actually took some snippets from the unity forums.. google search led me there lol
someone pls help ive been trying to fix this problem for hours now, im trying to crouch but im not able to uncrouch
imma send code now
i would really appreciate if anyone could help
im using a coroutine to transition my camera up and down when im crouching and swithching colliders at the same time, when i play the game, crouching is working but uncrouching is not working
i also cant move either after i implemented this
hey i hope this thing is related to coding but after i created the backbutton C# script i wanted to insert it to the game object so i can insert it to the button but for some reason i get this error any idea ?
it says the script should derive from monobehaviour
why do you want to insert to a game object
you add the script to the canvas
i think you can only add a script to a gameobject if it is derived from monobehviour
Yes.
Classes need to inherit mono behaviour to be used as a component.
This is beginner stuff, you should look for more tutorials first. 
Especially C# programming that you won't learn in unity tutorials but used everywhere.
your while loop is infinite because you never update heightDiff
i changed that
sorry wait
while (Mathf.Abs(heightDiff) > 0.01f)
{
heightDiff = targetHeight - currentHeight;
elapsedTime += Time.deltaTime;
float lerpValue = Mathf.Lerp(0.0f, 1.0f, elapsedTime * crouchSpeed);
cameraTransform.localPosition = new Vector3(cameraTransform.localPosition.x, currentHeight + (lerpValue * heightDiff), cameraTransform.localPosition.z);
yield return null;
you think it is okay now
but it still doesnt work
of course not, that makes no difference whatsoever
what else do you think i could do
for context i want to move the camera up and down when the player crouches
recalculate currentHeight might be favourite
you caught me yeah I am totally a beginner
sadly i don't know how
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
add the script to canvas, thats how i usually do it
i dont understand what do you mean
okay i wil try it
what makes you think that this line
heightDiff = targetHeight - currentHeight;
would produce different results each time it is run?
because current height keeps changing everytime the code runs because of lerp the camera transform and height diff would become zero at some point
no it does not
current height is a value type not a reference
it is set once and only once
you dont need to
heightDiff = targetHeight - cameraTransform.localPosition.y;
now it is using the correct value which changes
oh ok i will try now, thanks a lot for your help
had you bothered to add a few Debug.Log statements you would have seen this yourself a long time ago
oh now i also realized what you mean
and it still wont work
i dont know wtf is even wrong
Debug your values and find out
there is also no tutorials anywhere for adding crouching like this
sure i will try to use debug log more and find out
thanks for helping
i just understood that what im doing doesnt even make any sense
because the currentHeight variable keeps changing even when i jump
making realistic crouching isnt easy
u can use local positions
which you would recommend me to learn first i would like to know sorry for replying late
Unity Essentials followed by Junior Programmer
does using unity 2018 work on those too ?
or must be different versions
In general, yes. There may be small changes but the basics will be the same
Hey so i got the code working with the enemy following me, and and shooting but i need to move in its path while it follows me to shoot, i provided a pic below if that helps , its giving me the cold shoulder.
alright then i will give it a try
im just in a hurry because my college project AR app needs to be done by the next week
its weird , i just need it to face me and shoot, i tried rotating it to follow but no avail
and i don't know what to exactly focus on since there's UI and coding and 3D and audio to set up
there's many buttons too
animation channel dead ;-;
Ok?
error when trying to add Firebase to Unity 2D. Can someone help solve this problem?
InitializationException: Firebase app creation failed.
Firebase.FirebaseApp.CreateAndTrack (Firebase.FirebaseApp+CreateDelegate createDelegate, Firebase.FirebaseApp existingProxy) (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/macos_unity/x86_64/app/swig/Firebase.App_fixed.cs:2628)
Firebase.FirebaseApp.Create () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/macos_unity/x86_64/app/swig/Firebase.App_fixed.cs:2128)
Firebase.FirebaseApp.get_DefaultInstance () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/macos_unity/x86_64/app/swig/Firebase.App_fixed.cs:2103)
Firebase.Auth.FirebaseAuth.get_DefaultInstance () (at /Users/runner/work/firebase-unity-sdk/firebase-unity-sdk/macos_unity/x86_64/auth/swig/Firebase.Auth_fixed.cs:4100)
AuthManager.InitializeFirebase () (at Assets/Login Scene/Scripts/AuthManager.cs:101)
AuthManager+<CheckAndFixDependencies>d__19.MoveNext () (at Assets/Login Scene/Scripts/AuthManager.cs:55)
what is your hardware and OS setup?
My operating system is Windows 10 Home, 64-bit. The processor is an Intel Xeon E5-2678 v3 at 2.50 GHz with 4 GB of RAM. I'm using Unity 2022.3.24f1 and the latest version of the Firebase SDK.
well the version of the SDK you are using is obviously for MacOS
'firebase-unity-sdk/macos_unity/x86_64/'
Not just MacOS but Intel Mac hardware
I'm not sure if the Xeon is even supported
Then how can we solve this problem?
we cannot solve this problem. You could start by reading the Firebase SDK documentation
trying to remap floats but I see that Mathf.InverseLerp is clamped 0-1, and there's no unclamped version of inverse lerp like there is for lerp. anyone got a better way of remapping?
this is my function rn:
public static float RemapFloat(float value ,float initialMin, float initialMax, float targetMin, float targetMax)
{
float t = Mathf.InverseLerp(initialMin, initialMax, value);
return Mathf.LerpUnclamped(targetMin, targetMax, t);
}
I am working with game managers using start/game/end screens to function in a triangle by pressing buttons. These were working, but now the start screen doesn't show up at all and the button doesn't work and I'm not quite sure on why. Everything looks correct? Very confused.
do you have an EventSystem i think it was called, in your hierarchy?
put a debug.log into the LoadGameScene at the beginning to check if it runs
it runs when pressed
So it's still sensing input but not changing scenes for some reason
whats the rest of the code in the LoadGameScene method
`public void LoadStartScene() // Game START
{
SceneManager.LoadScene(0);
}
public void LoadGameScene() // Game GAME
{
SceneManager.LoadScene(1);
Debug.Log("Test");
}
public void LoadEndScene() // Game END
{
SceneManager.LoadScene(2);
}`
do you have any errors in the console?
nope
screenshot your build settings window
So your indexes are wrong
oh huh thats weird
i think start is supposed to be 0
maybe thats what is causing it?
how do i fix that
move it
ahhhh that fixed it! Thanks so much!! 
I have code, that applies on all of the text & all of the objects on the desk```c#
figure.transform.localScale = new Vector3(size, size, size);
text.transform.SetParent(figure.transform);
text.transform.localPosition = new Vector3(0, size / 2, 0);
I expect, what i will have texture conflict named overlay, but i have this. Please, feel free to ask stupid questions like "is the size int?"(it's float), because i can make a mistake even in so simple things
Just because scale is size doesn't mean the actual model size is size
If the size is indeed <= size then placing the text slightly higher should be enough
Good point, you should use the bounds from the renderer of the figure to calculate the local position of the text
ok I made my remap unclamped using math but now it can't handle inverse ranges.
like if I do RemapFloat(x,0,10,1,0) it breaks because 1-0 isn't a valid range.
is there a way to fix this?
public static float RemapFloat(float value ,float initialMin, float initialMax, float targetMin, float targetMax)
{
float output = targetMin + (targetMax - initialMin) * ((value - initialMin) / (initialMax - initialMin));
if(float.IsNaN(output) || float.IsInfinity(output))
{
Debug.LogWarning("remap failed, output is infinity or NaN");
}
return output;
}
your logic is incorrect. It should be
value = x as a normalized percentage of initialMax-initialMin
result = Lerp of targetMin, targetMax, value
use inverse Lerp and Lerp, job done
that had the issue of being clamped
@languid spire I thought that too but inverselerp is clamped (and so is Lerp, but there is LerpUnclamped)
Could make your own InverseLerpUnclamped though
ok, then my solution
if I knew how to math I would xD
you know the best way to do math? Pen and Paper
if you cannot do it in your head
no I mean like, how does inverse lerp even work
This seems to cover lerp, invlerp and their combination: remap
https://www.gamedev.net/articles/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
I mean, it's the first result on google
Yeah that
oh
First result with 'inverse lerp' 
guess I was making it too difficult
should have just used "inverse lerp formula"
googling is an art, and sometimes I suck at art 
pretty much what I said here #💻┃code-beginner message
guess what, programming is an art as well
can anyone add Firebase to Android Unity 2D? and give me control?
no, i just needed 2 take account 2 scale factor & working formula is just 0.5
https://paste.ofcode.org/5VeBAPKQVhvmYQLjGcdfhU
https://paste.ofcode.org/drhxYQ2ZXRvyZEBxBDAjvx
https://paste.ofcode.org/5D4Sgkum4GfenskMauTnQu
https://paste.ofcode.org/axPsbAazd98cGNa4gNZJyj
I have a tower defence game that i am trying to make but for some reason my retry button inside my Pause menu and my Game over scene dont reload the level Properly. Enemies dont spawn in, my timer for the next wave is stuck and the scene itself just doesnt wanna load in properly. The only time the scene actually loads in properly is when i pause the game before the timer reaches 0 and the enemies spawn in. That is when the scene will reload and it will go back to the point where it counts down until enemies spawn.
Same with when i go to the main menu from the Pause screen. When i go to main menu with the click of the button i made, it takes me to the main menu. I then go to level select, then i go to the level i was in and the same thing happns. If enemies spawn, the level cant reload properly after i go to menu and then back to level. If the timer hasnt reached 0 yet and no enemies spawn, going from Pause menu, to main menu, to level again is suddenly fine? I am not really sure why that happens and could really use some help on this. Hope i explained things well enough here? ^^'
public IEnumerator ChangeCameraPosition(Transform cameraTransform, float lerpTime, bool lockAfterLerp) {
canInteract = false;
canLook = false;
canMove = false;
float t = 0f;
Transform startingTransform = _camera.transform;
while (t < lerpTime) {
_camera.transform.position =
Vector3.Lerp(startingTransform.position, cameraTransform.position, t / lerpTime);
_camera.transform.rotation =
Quaternion.Lerp(startingTransform.rotation, cameraTransform.rotation, t / lerpTime);
t += Time.deltaTime;
yield return null;
}
_camera.transform.position = cameraTransform.position;
_camera.transform.rotation = cameraTransform.rotation;
if (!lockAfterLerp) {
canInteract = true; //This 3 lines in this if
canLook = true;
canMove = true;
};
yield return null;
}
``` why does it take so long to run those 3 lines, it looks like the lerp is finished but it takes like one second to run those lines
when I click on configure nothing happens how can I fix this?
The code is gonna take as long as you specify it to
lerpTime
no?
yea but it takes like 0.5 seconds after the lerp looks finished to acctually run those 3 lines
i'll record a vid
this it how it looks, im moving the mouse around after i click the exit button
I dont see any mistakes in the code, you could debug it to see if it actually takes longer but it should be pretty much exactly the lerpTime
Does anybody know what kind of coding I have to to implement a pikmin like script?
unity is acting up again
im working on a pause button systemm
and for some reason it functions perfectly in my main game scene but in every other scene it doesnt work
well theres probably something different in those other scenes then
just gotta figure out what it is
could the other scenes be missing an event system? unity doesn't usually act up by itself
if not that, there's definitely still something different between the scenes as pointed out
yep turns out i was missing an event system in the second scene
added it to the player
player?
may not matter but usually you want the event system to be an own gameObject. otherwise you may disable or remove it by accident
it looks like it's finished but it waits a little bit, it kind of prints ended on time, but in game it doesn't seem like it
Im so tired, i tried to make screenshot taking in game (at game over), but image is always based on screen size (texture.ReadPixels) and of i dunno how to make in 1080x1920 like it supposed to be
eh everything is tied to the player object as its the most simplest
could work but doesn't sound like the best design choise
How do you want to handle if somebody has a bigger screen than that? crop the image, stretch it?
could look for a screenshot tool on the asset store
I dunno, i just wanna take photo of an object in game, maybe even not with main camera, but i dunno how
if lerpTime is 1 then it does take one second to run those lines
no, like it LOOKS like 0.5 after it LOOKS finished, it does change it after 1 second
is lerpTime set to 1 second?
as I said, you should debug and check what the actual time taken is
Or at least debug.Log(lerpTime)
To make sure you call it only once with the correct time
does anyone know a simple way to make your character not jump while crouching, i mean you should not be able to jump if u press space while crouching
if (Input.GetKey(crouchKey))
{
state = MovementState.CrouchState;
moveSpeed = crouchSpeed;
}
what can i add in here
there is a function call jump() and a variable called isJumping
and keycode called jumpkey
oh wait
yeah im so dumb
i didnt think of this
thanks very much
i finally finished my character controller
That’s the code making my goblin move and follow player
Hey guys so I’m working on a 2d platformer game and I’ve added a goblin as my enemy but for some reason he’s floating and doing weird stuff
i highly doubt anyones gonna help you if you dont format it correctly
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
no worries, its just hard to read
also for next time, if you want to make a screenshot just do win + shift + s and then ctrl + v in this chat to post it
It’s my school computer soo cant screen shot and post on discord
Cant access discord on schools computer
Once I paste code on hate bin how do I share link?
just post it here
GDL Paste - ebigadayaj
yeah
u can use pascal case for public variables @nimble wigeon
use public RigidBody, private rigidBody
So instead of doing serialize field I just do public Rigidbody rb;?
no use serialize field, i meant for public variables use pascal case where all words start capital, rn u are using camel case for everything which first words start with small and rest start with caps
Oh is pascal better?
I just do that because in my CSA class they told us to always use camel case
no it is used to distinguish between private and public variables
Ok ty
But do u see anything wrong with the code? I’ll see if I can see video of what is wrong with my enemy
where do you have this script attached
It’s attached too the goblin
He’s floating and when he crashes into my player he pushes the whole background and tilemap
its a bit messy
if(health <= 0)
{
goblinAnim.SetBool("isDead", true);
Destroy(gameObject);
}
why does this need to be checked every frame?
Why is it not at the end of TakeDamage()
private void Flip()
{
Vector3 scale = transform.localScale;
if (player.transform.position.x > transform.position.x)
{
scale.x = 1;
}
else
{
scale.x = -1;
}
}
i think this will work
your script is very incomplete you also never used the take damage function anywhere
but i think u can also put that code in the end of take damage
did you fix it?
did you just took a screenshot of a screenshot?
why not just send the screenshot you made on pc
what is InteractableObject?
whats that error?
What does the error say
- use TryGetComponent instead of two separate GetComponent calls
- do you have a component called InteractableObject
https://youtu.be/_GzSfnJNNI4?si=6MzcF5E64IgYR_JF
I am following this tutorial
#survivalgame #tutorial #unity
In this tutorial series, we will create a 3D survival game with Unity & C# as the scripting language.
We will start with basic FPS movement, inventory building, and crafting systems.
Learn how to pick up items and more.
Little by little, we are going to add different features that are common to survival open-world...
Oh boy is the counter about to go up?
check the console in Unity and see
Are you starting from Part 3 of a tutorial series?
you haven't answered my question yet, do you have a component called InteractableObject
idk I am following a tutorial 🥺
try paying attention to it then?
then you should know, unless you arent following it but doing it blindly
What is InteractableObject
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
the video has it
no ?
ohh that script I have that as well its basic for naming tress and diff stuff in evironment
whats it called
that script
lmao the video covers it after writing that code apparently
InteractableObject
so just keep watching the video i guess
what a terribly structured tutorial series
This is not a tutorial you should be following. This is a tutorial for people who already know the engine and need to see the concepts put together into a large project
This is more about the workflow and project structure. This is not something you follow verbatim.
Still, they do have the script in the tutorial and you don't so it counts.
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 159
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-4-30
do u know a better tutotrial?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
what does that even mean, also like i already said !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
you know what whatever thats fine, no where in the message it said use a screenshot but its OK, its fine for me
whats the problem with the code?
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
let me fix that
you also need to get your !IDE configured
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
my player is floating and when i play the game i cant jump because the player is floating i tried moving it down but it goes back up how do i fix this?
move the mesh only, down
how do you move the mesh down?
move ch32_nonPBR down
Now that I fixed that issue thanks, why can't I jump? I have the script but I can't jump
I'm not a mind reader, how should I know?
🪄 🔮
need to show the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
public float jumpHeight = 3f;
Vector3 velocity;
bool isGrounded;
// Update is called once per frame
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
You don't have any Layer selected in your groundMask
why I guess you can't jump
- your inputs aren't being read / used correctly
- your conditional (isGrounded for example) is never true
- your forces are wrong/ inadequate
- other (missing layermask for example, see [2])
btw, if this is the Unity Character Controller it already has a ground check built-in https://docs.unity3d.com/ScriptReference/CharacterController-isGrounded.html
nooooo
this is like the worst way to use grounded
yes , only works whilist the Move is called
lol ¯_(ツ)_/¯
its very finnicky
ohh.. yea ive never not had my Move() function not running in update.. so i never noticed :S
also only works when controller is exactly touching another collider and u cant filter out the layers
its a mess
ahh, okay.. noted
CheckSphere is pretty good, though personally would use OverlapNonalloc
instead of return cc.isground just return OverLap returned colliders > 0
It works perfectly fine as long as:
- You are calling
Moveexactly once every Update - You are properly applying gravity even when grounded
- You have no solid objects other than ground
why use Overlap when you can just use Check
there was a specific reason , forgot what it was tbh. But I did try both
iirc even the unity third person character controller uses overlap instead
it works fine even if you call Move more than once with the caveat that you can only use it after moving along the Y axis. if you only move horizontally then it may not be considered grounded
it's a waste to do so unless you need the info about the collider(s) found. CheckSphere does the same thing but doesn't return the collider, it just returns true if a collider is found
hmm yeah true , I gotta go back n check why I ended up with using Overlap instead
now that i think about it i do have a weird groundcheck issue here
was trying to make a mechanic when u land.. so ur head would bob.. so (rationally thinking)
i thought if i set a bool at the end of the frame.. and then check the controller's bool against it I would find out when i land..
ofc that didn't work.. but when i cached it at the beginning of the frame.. (before the conditional) it works as i suspected it to work the other way
intereesting.. thats all i know
when ever i start the game why does my player spawn above the ground and when i stop the player goes back on the ground
if i do it this way (the way it makes sense in my head) it doesnt work
skin of the collider? script? who knows..
It looks like your mesh is just centered in the collider, the feet are nowhere near where the collider would collide.
oh yea ^ if thats ur player.. its just b/c the mesh's feet aren't at the bottom of the capsule
huh ? thought that was fixed by telling them to move mesh down
#💻┃code-beginner message
not working
well, if it has been moved down.. and its standing a bit off hte ground tahts the skin width
either lower it.. or start the game.. move the mesh down while its playing.. to get ur real Y offset.. and paste it back in after u stop
ur scale is weird too
should try to keep a Uniform scale on Root gameobjects, especially Rigidbodys and CharacterControllers
what sort of programming is that? 16 different scripts for just having a speed value for the movement?
just put it in 1
jesus
its the Composition workflow guys
{
//put stats
}```
need
Walk Controller Settings Sprint Controller Settings Idle Controller Settings
all with different values, best ScriptableObject approach
having 1 is not good enough
still need a struct/class on it 😛
well you don't need it , but probably smarter to
Oh i mean inside
i actually have a struct version as well..
this way they are easier to copy over for mutable data
i was experimenting with different methods of storing the settings
still havent figured out whats best to use
I like to encode all my settings into colors and save them as texture2d. XD
lmfao 🤣
im going to store all my stats in QR codes
you actually gave me a stupid idea i can justify atleast a few hours of procrastination to indulge
It's a good idea whatever it is.
Vince McMahon says "There is no stupid idea"
why is it still floating?? i dont understand
You still aren't at the bottom of the collider.
Maybe use orto view when setting it
its always going to float a little
just drop ur mesh down until it touches the ground..
The y of the center for your CharacterController is -.04
Also, the mesh is likely up a little
what should it be
Well, 0
Moving it down will raise your mesh up
Because the CC is a collider
im trying to make a custom editor script. i want to put these two objects into this template prefab. however when the new prefab is created, it only does metarig. this is after debug logs are telling me there are two child objects and telling me their correct names. how can i fix this?
private void CreatePrefab()
{
GameObject newPrefab = Instantiate(prefab);
GameObject newFBXObject = Instantiate(fbxObject);
foreach (Transform child in newFBXObject.transform)
{
GameObject newChild = Instantiate(child.gameObject);
newChild.transform.SetParent(newPrefab.transform, true);
}
when i drag my player to the ground it bounces back up??
u should be dragging the mesh (graphics)
u dont drag ur player into the ground.. ofc that will pop back up.. b/c colliders dont like to be inside other colliders
im dragging the Mesh not my SpawnCampController <- CharacterController
if its popping back up theres something in ur code/animations thats positioning it automatically (if ur dragging the graphics like you should be doing.. and not an actual collider)
Are you changing it during runtime?
yes
u telling me this guy pops back up from the ground?
is it better to calculate camera physics in FixedUpdate(), or multiply X and Y values by Time.DeltaTime ?
only way that would happen if yu have script/animation moving it back up
then ur animations ^ must be doing it..
camera physics?
why
yes, the rotation.
how can i remove the animation
you can create an empty parent.. around the mesh and move it down instead
