#💻┃code-beginner
1 messages · Page 428 of 1
Debug.DrawRay
To visualize stuff like that cross product or the new direction that you're adding to the position
I didn't know that was a thing
then you remember incorrectly possibly it was created by an asset you imported
probably yeah
Dont think that joint has a way for it to break like this. You could try to configure its break force through trial and error but I wouldnt. Maybe just delete the joint yourself when it's far enough away
Configuring joints are always a pain in the ass imo
Isn't there a joint that's more specific to what I need?
Also, I agree I don't want to tweak parameters like a monkey all day 🐵
Cause I want to make a game where realistic physics is really important
So, if I just delete the joint when it's far away without tweaking the velocity/acceleration in a realistic way the game might just not feel as funny to play
🤷♂️ look through the joints and see for yourself if any fit your use case. I vaguely remember from others that 2d joints are way more limited than 3d, you can always make your own. Though I fail to see how you want realism here when you're using a joint for a nail hanging off something
@eternal needle welp that literally showed me exactly what was wrong, the result needed to be inversed so *-1 and it's done
thanks 
it's not just a nail, it was an analogy
I can't explain everything here without it being hard to understand
but it works just like a nail attached to something
Np, not like I did much besides tell you to debug it 😂
Well then I cant answer your true problem if you're gonna obfuscate it.
My answer is still the same, look through the existing joints and see for yourself.
it's the simple things that always fly over my head
I didn't obfuscate it tho...
I'm literally asking for help so I don't have to go through all of the joints and test every parameter, cause I already went through almost all of them and didn't find anything that helped my problem, otherwise I wouldn't be asking for help here...
How would I effectively modify the environment settings and skybox through code? I don't see how I can access the scene 😅
You're not being helpful at all with this attitude, @eternal needle
Anyway, I'll deal with it myself
have a nice week
What attitude? It takes minutes to look through the docs on what the joints do. You asked if there was a joint specific to your needs, but didnt really describe what your needs were exactly.
I already answered on what you could do to for your initial question but you simply didnt want to "for realism"
someone seems to have a space/ time dislocation problem, today is Wednesday
🤷♂️ probably just upset that their problem couldnt be directly solved. Which tends to happen if people dont state the actual problem.
First it was breaking a joint after a certain distance, which I answered. That didnt suit their true use case so the solution was dismissed.
Are you looking for this https://docs.unity3d.com/ScriptReference/RenderSettings-skybox.html
There should also be a few tutorials out there on this
maybe for you it's a minute, for me it's hours of testing and watching tutorials
I already said my problem is exactly like a hanging nail physics (an analogy, my game is NOT nails hanging)
True, I'm still trying to figure out the nail analogy. I honestly have no idea what that means
And what's the issue with what I said about breaking the joint after a set distance? Because if you want realism, you shouldnt be using joints in the first place.
It would be cutting into the mesh and sticking whatever the nail is, in
Maybe that's what I need to do
The problem is that this would probably not consider all the friction that the nail is going through as it comes out of a hole
how can i make the nail stick, then?
Do i do this literally and unity would get the physics right?
You should definitely reconsider what you're actually doing, because most games will fake everything. I dont think it's really possible to make a "nail in wood" scenario without massive issues
Even if you set the friction really high, it's not realistic. If the objects rub against each other itll be sticking almost, while this sticking behaviour was only meant for when the nail was inside.
If you use a joint, theres this sudden magic force pulling the nail back inside which obviously doesnt exist in real life
Maybe it's just a matter of simulating physics using vectorial calculus then
I didn't want to do that, since its a lot of work, but this seems to be the only way
I don't think I'll be able to achieve what I want without making the nail physics, I really need realistic physics to achieve it
Anyway, thank you so much for your help!
Have a nice week ❤️
For some reason theres frames where my character is thru the ground and i have no clue why that is and ive been playing around with it for the past 15 mins trying to figure it out https://paste.ofcode.org/a8Msv8uq8JW5NsCFJMppK
im trying to change the material on a TextMeshProUGUI via code but cant seem to do it. Google also doesnt seem to have a good answer.
public TextMeshProUGUI costText;
public Material costMetTxt;
public Material costNotMetTxt;
public void SetCostText(bool costMet)
{
costText.material = costMet ? costMetTxt : costNotMetTxt;
}
this seems like the most straightforward way to do it, but it visually does nothing
question, is setting the timescale to 0 the best way to pause a game? what if i make a main menu , should it just overlay the game or be in a different scene untill i press play and it makes the timescale 1 again?
Start menu should be a different scene and main menu is dependent on the effect you want
Start menu before you actually start playing should be a seperate scene
I havent got that far im still a beginner 🙂
make sure it is the first one in the build settings, the one with an index of 0
if im on the main menu scene it wont load the actual game scene right?
TimeScale is fine for a basic pause
itll stay unactivated ig
You decide what loads and when, all other scenes are not active when 1 is active usually
yes (Theres probably a way to have multiple for like separate physics calculations but thats a whole other thing)
you said usually so how can there be more than one running at a time?
I edited the messege
another question
what if
i had a character with an inventory
moving from one scene to another
how would i make it so that the contents of his inventory stay the same ?
use DontDestroyOnLoad(), but saving it into like a file would be good (A ScriptableObject perhaps)
fixed, turns out i can change the color without changing the material lul
what does that method do
When a new scene is loaded, all the object in the scene get destroyed, and all the objects from the new scene spawn, DontDestroyOnLoad prevents an object from getting destroyed each time a new scene is loaded
im guessing i put the gameobject in the brackets right?
Yes, the thing you want to stay
https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
okay
public void SpawnAndFireBullets()
{
StartCoroutine(StartSpawning());
}
private IEnumerator StartSpawning()
{
foreach (var point in spawnPoints)
{
var playerPosition = PlayerManager.Instance.player.transform.position;
var offsetedPosition = playerPosition + Random.insideUnitSphere * 3;
var directionToOffsetedPosition = (offsetedPosition - point.position).normalized;
var projectile = BGPoolManager.Instance.GetFromPool(ObjectType.ZSOLTAR_RIFLE_PROJECTILE);
projectile.transform.position = point.transform.position;
projectile.transform.forward = directionToOffsetedPosition;
if (projectile && projectile.TryGetComponent(out ExplodeProjectileBullet bullet))
{
Debug.Log("Time Scale: " + Time.timeScale);
Debug.Log("shooting bullet");
bullet.StartCoroutine(bullet.ShootBullet(directionToOffsetedPosition));
yield return new WaitForSeconds(delayBeetwenEachSpawn);
Debug.Log("after wait for seconds");
}
}
}
I have a function SpawnAndFireBullets() that I am hooking in UnityEvent that is starting a coroutine, althought it fires only one bullet and gets stuck at WaitForSeconds. The Debug.Log after wait for seconds isn't printed. The game object is not being destroyed, time scale is 1, what am i doing wrong. Delay between each spawn is 0.3f
I really need help on this one i havent found a single way to resolve this issue, all i tried only broke it or made it worse
Is the terrain marked as Ground
yes
oh wait youre talking about the crouching?
That makes sense because youre just setting the new size right away, without any calculations to bring the player up a little
Oh no i have to bring him down a little for it to work
im having a bit of a problem , so i have a chargeable bow which depending on how long you charged it for , it will deal that much dmg etc but im not sure on how to mkae only the bows dmg to change and not the others since seems like when i use my bow and yk i shoot the enemies , then go buy the pistol from the shop , it only deals 1 dmg so im asking on how to make it so only the bow can have that dmg since i have a SO that handles the firerate , dmg etc and in second ss it shows that im putting the weaponSO.DMG = ArrowDMG which is why the dmg gets changed as well , im not sure on how to make it so only the bow has that dmg
Heres an example
I know but when he stands back up (Heigh changed) you dont bring him up
Yes, can you try doing the same thing for standing up?
Yeah when hes standing up its meant to be 0
Like here
Well you can also change the transform position directly, I dont know the best approach though
Maybe lerp the height so he doing go through the ground too much
Yeah i was gonna add lerping into everything a bit later on to smoothen it out but atm i want the base to work flawlessly
I tried the transform method and everything that could break broke
😂
did you do (0, y, 0) or something
is it possible delayBeetwenEachSpawn is set to something larger like in inspector? id just do a sanity check on all those variables like how many points are in spawnPoints, what delayBeetwenEachSpawn is set to. Is it always entering the if statement? It will be an issue if this loops through everything and never hits a yield
sorry for not claryfing, i fixed the issue - it was very rookie mistake of not saving a .cs file in my IDE
Yes i changed the center of the Character Controller so the hitboxes changed accordingly
anyone know this?
when you change positions do, do Vector3(position.x, position.y + riseAmount, position.z)
Hard to say much tho because im unsure
Arrow damage = weapon.arrowdamage
Hi
To save some data when I change scene, I create a Prefab that call before all scenes. Do I put my main camera and my player gameobject in this prefab or just some data like inventory ?
Why does it need to be an object
It can be a static class
a lot of this doesnt make sense, you could save data in many ways. Like an object that exists in DDOL and just holds what you need
https://paste.ofcode.org/a8Msv8uq8JW5NsCFJMppK anything of "movement." is in another file btw
There are tutorials for save systems if you're curious on how to make one
I read in some forums different methods to save data between scenes. Someone do a prescene with DDOL and another one do a prefab.
Prefab would be an asset. I'm assuming you're using the Singleton pattern with some object that isn't destroyed on loading a new scene. You can choose to store some important data, the objects or whatnot. It's really up to you what you'd want to persist.
im sure people do lots of things, but saving data in a prefab is probably the worst
Oh shit 😭
.fm
So you advice to do the system of do a prescene at first with DDOL ?
Oh wrong server
The only benefit to that would be that you can visualize the current game state in the inspector
You could also just make a script that specifically does that though, or use OnGUI etc
it depends entirely on what you want, and what you're saving. Generally saving is associated with having an object in DDOL but its not required. What are you actually saving, and what was the relation with the player because you mentioned that initially
The player can also hold its own data and persist between scenes
id hardly call this a benefit. And "saving" to a prefab is only temporary as this is an asset. Theres really no reason to do this
Thats not the positon, thats the center, like a center of a collider
But is it better to put in all scenes the prefab of the player and the main camera or try to save it in DDOL ?
(I'm lost on what DDOL means I've never heard this term?)
again, this makes no sense. If you want to clarify further, try answering what i asked #💻┃code-beginner message
Usually you dont wanna put your player in every single scene, as you can just spawn it at runtime
the internal scene, Dont Destroy On Load
Ohhh
I just woke up mb
Okay thanks guys, I'll see how do these many things

What does it means ?
well i dont know if you think i answered your question, i was trying to get more clarification so i could answer it properly. But if you feel you know what to do now then carry on
yeah thats what i change
The goal of my question was to know if use a prefab to save data was a good idea. But now, I know there is a better option so what I need to do
If you could tell us what youre trying to save it'd be easier to give suggestions
that might work.
I want to save my inventory, like my weapons or coins, and the health of the player for the moment
And also teleport the player to a specific position after load the new scene
Do you want the data to persist between sessions
OK so you understand serialization and how to save/load to a data class?
Serialization**
Lmao
But I want to save data in JSON only in some locations and not always between scenes
Yes
Oh I see
As in you don't want saving tied to scene change?
When are you wanting to save then
Yes exactly
In some locations when we pressed a specific key
So you have now changed completely what you first asked for?
Not yet, I do a eat break lol
Its only necessary to load the save data once when bdginning, then you can make the player DDOL.
The player can then use a spawn manager to get "spawned" at where it should be on the next scene
So with a prescene that's loaded before all scenes for example ?
And you put this script on what gameobject ?
Would be preferred, a main menu basically
In a gameobject of the actual scene or the future scene ?
You could also make each individual scene load the save data redundantly (or check if the data == null and load data if it hasn't been loaded yet)
Why do this redundantly and not juste at the beginning when the player enter in the scene ?
And save it again when he'll move to a new scene ?
I'd just make an empty object called spawn manager in every scene that you play in
When you load into the scene directly in the editor you will want your save data to speed up testing
And changed the transform of the player to this game object right ?
Well I guess you could do that sure
I'd make a seperate spawn point object personally
Yes but at the end, it will be optimised to do this just at the beginning and when the player moves to a new scene no ?
Then you request a spawnpoint from the spawn manager as the player when you enter the scene
Yes that's why I said you can instead just check if there is no save data loaded and only load if it hasn't been yet
No point in reloading save data between scenes
I'm not sure I understand...
So with the spawn manager, I teleport the player to the spawnpoint ?
Yes
So you'd do that to an Update() function or Start() ?
Player.cs
OnSceneChange:
Find the spawn manager
Transform.Position = spawnmanager.getspawnpoint()
Spawnmanager.cs:
Return spawnpoint.transform.Position
How can we know we have change scene ?
So with OnSceneLoaded ?
void Start()
{
SceneManager.sceneLoaded += OnSceneLoaded;
}
// called second
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
var spawnManager = // find the spawn manager somehow (singleton, findanyobjectoftype, gameobject.find, etc..)
transform.position = spawnManager.GetSpawnpoint();
}
today I learned that SceneManager has that
what are the parameters of OnSceneLoaded for ?
Scene scene is just the scene that is loaded, LoadSceneMode tells you if the scene is loaded single or additively.
In this case it doesn't matter here, you just want to do something when the scene is loaded
Scene = the scene that was loaded
LoadSceneMode = whether scene was loaded additively or single
well you probably want to ignore if the scene was loaded additively
So you put this in the player script right ?
Using Cinemachine 3, should i reference the main camera (with brain) or the CinemachineCamera to perform fov operations?
I don't think it will even let you change the FOV on the unity camera, cinemachine overrides it
o> noted
Always the virtual camera
anybody know why when my cube falls it doesnt rotate? it stays still
Why are you expecting it to rotate? Are you actually putting any force on it that would cause it to?
i mean i dont rerally think it matters tbh
well having 0 angular drag would make it pretty unlikely to rotate wouldnt it
its also a cube falling straight down
unless something pushes it, there's no reason it would rotate
its fine i just thought it should have been rotating if falling but my end result i want it still so it doesnt matter to much anyway
physics isn't my strong suit 😅
https://docs.unity3d.com/ScriptReference/Rigidbody-angularDrag.html
angular drag slows it down from rotating
bruh lol
try making it start at a slight angle

well i was right in the wrong kind of way
nah its fine small problem i dont really care about lol
im selecting a random element from an array but i need to check if there is an item in it
if there is, it needs to select another element
what is the best way to do this
have a list of slots that have an item in them? and select from that one
I dont know where to ask this question sorry if wrong. How To Make "Enemy for fps shooting game" he just follow me and shoot at me.
i wanna know basics of ai, nav mesh etc.
Are you allowed to modify or move the elements of the list/array?
If you rearrange the null elements to the end of the list, you could set your random selection to indices in the array that would contain actual elements.
i changed my code, thanks @ivory bobcat @cosmic quail
i thought about it but its easier this way
does anyone know how to fix this?
break the problem down into multiple parts
- enemy
- having enemy follow you
- having enemy shoot at you
start by creating an enemy with their collider and model. make a new script called Enemy AI, attach it to the enemy.
in the script, under update, you may raycast between the enemy's head and player's head. if there's no object in the way, the enemy has seen the player and can start moving towards the player. to keep track of if the enemy has seen the player you can look into a Finite State machine.
for now dont take pathfinding into consideration, just move the enemy position to the player first and make the enemy shoot in the direction of the player.
once you have all the basics down you can substitute the code for navmesh pathfinding. Unity has a package for it already, this is something you shoul research by yourself seperate from the enemy code. once youre familiar with navmesh, one way to go about it is changing the target gameobject based on whether the enemy has seen the player.
we dont know what you're talking about
ask more concise questions
Thanks for your time.
tldr go learn unity navmesh first
everything will click once you play around with it enough
This is the code channel. It looks like you're asking about learning ai related content, which might be valid in #💻┃unity-talk and #🤖┃ai-navigation
I replied to the message I sent that shows with what I need help-
as in
i dont understand what you've typed in that message
you only want to change the bow's damage but not the gun's damage?
why arent the bow and guns from different scriptable objects?
They are , I have a Bow SO and a Pistol SO as seen in the video
I only want to change the bows DMG and not the other guns since I have a chargeable bow rn and it deals DMG based on how long you charged your bow and I'm doing WeaponSO.DMG since I didn't know how to change only bows DMG and not the other guns
Well, you would have individual SOs for each weapon type, and then do not change their values at runtime at all. The mutable data should be store in a class, while only the defaults are in the SO
Wdym the defaults? Like the name , description etc?
Like the values you set in the inspector.
Something like MaxHealth and BaseDamage
Oh I have a float in my WeaponSO named DMG which is used for the dmg
Ok. And as long as that doesn't change at runtime that is fine. Now you just need to create an asset for each weapon type
Bow should have its own asset
I alr have them dwdw
This will create an asset instance from the WeaponSO
For both Bow and Pistol
Ok perfect. Then changing that instance will NOT affect any other weapon
I think since I'm doing WeaponSO(it's a reference to the SO) = arrowDMG , it might change the dmg of the pistol as well for some reason
Yeah, you do not want to change the values in code
You want to change them in the inspector
Check what's arrowDMG
I kinda need to do it in code lol
Then it doesn't sound like a good use for an SO
Just use a POCO
What's an POCO
A plain class
"Plain ol' C# Object"
A class that doesn't extend anything
its entire purpose is to pass data around and have instances and that's it
Because you are doing the one thing I said not to do, which is change the values at runtime
Data like DMG etc?
That is data, yes
Literally whatever data you want
that's the point of it
It's a data structure that you make
So I just make a class and put all the data I need in there then use it for when I'm trying to change a weapons DMG?
Yes
have a problem when my cube hits the obstacle my cubes movement is supposed to stop slighlty but it keeps going
Add a debug log to see if the code enter the condition
So what I'm understanding
• have a class that holds the different data I need
• use the DMG field when changing a weapons DMG
• I don't need a SO for the data or I need it
Sorry I'm trying my best to understand 
you can edit posts on discord
Yes to all of that
You can think of the SO as a "Read only database". It lets you define what a weapon is in a file in your project. When the game starts, you copy that data over to a POCO that you can change freely. This way your weapon's base stats never change.
Can you show your movement script ?
the one you're trying to disable
Nah, i mean the code
Okay, so, if this log is inside the if condition, then whichever playermovement1 you are referencing in the movement variable gets disabled
OOOH so I can still keep my SO and reference it in that POCO or make new fields inside the POCO then set the SO data to the POCO data?
If you're not seeing it be disabled, then either:
A) Something else is enabling it
B) movement is not the one you think it is
You probably set a velocity to your rigibody, hence, disabling the script won't stop your player
The SO's data will never ever change
how do I fix this error?
You do not want to change any data in an SO at runtime
Open that file, look for the thing underlined in red, and fix your syntax
no it gets disabled
it just keeps movinmg
moving
but i want it to slow down and stop
after i ran it
Okay, so what actually moves the object then?
Is there a way to check if a meshrenderer has a certain material? I've tried checking meshRenderer.material but since it returns an instance I can't compare it to the material I've assigned in editor
That is what my original suggestion was, yes
There's nothing underlined in red in the code
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Then you need to configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
DOUBLE KILL
Alright then I leave the SO data out of the POCO and make new data like DMG and fire rate then make a reference to that POCO in my WeaponShooting script so I can ya control what which DMG has the weapon
ok I'll look up how to do that I thought I already did
Pretty sure you have been told to configure your ide many times maryo
If there is no underlining, then it is not done
Yes. You can copy data from the SO to the POCO, but never the other way around
The first choice or the second one?
Oh alright alright perfect , I think I understood
I think you might be looking for .sharedMaterial
It's because I thought I already did but I guess I didn't
My brain is expanding 
Wha'ts the difference if I may ask?
The second sounds better
I have configured it I see the things online in red now I didn't have to do anything
Alrighty , hopefully I understood it correctly 
I'm not great with with mesh/material stuff, and it's been a while since I've touched it 😅
You may have more luck researching it on your own than me trying to verbalize the mess in my head
_itemGameObject = new GameObject
{
transform =
{
position = Vector3.zero,
parent = transform
}
};
Why isn't it working? It supposed to set the position of a freshly created game object to zeros, but... it doesn't
something definitely feels off here
I would be interested to hear if that does work for you though - I've never tried to compare a material to one from an inspector field as you are
how does
= {} work?
ive never encountered something like that
I don't even think this will compile
Like 90% sure it doesn't
it's called object initializer
it wont, transform within transform
Yeah but you literally cannot create a transform with new and also you aren't using new
So, no, this isn't a valid object initializer
I don't know how to fix it
you can???
it is creating, but the position isn't setting
You can create a GameObject with new
but not a Transform
It does work yes
Solid!! Very cool 🎉
Thank you!
I mean, it is compiling
Well, how can I fix it then?
Create the object, then change the properties of its transform in the next line
Literally the same result
and what is that result?
the 3 blue are connected how do I disconnect them?
It supposed to set the position of a freshly created game object to zeros, but... it doesn't
Okay, so what does it do
Set it's to some randomly coordinates, somewhere in the screen's edge
connected to what??
that's definetly not zeros
each other
thats weird..hmm maybe try right click and Unpacking
Create a new empty game object, with no parent. Put it at 0,0,0 then visually check if it's at the same position as this object
I don't see that
huh..what happens when you right click it
Looks like it was setting it to the zeros of the scene, but not of the parent. Fixed it by changing Vector3.zero to transform.position
Thank you
I think that's the wrong wording but when I try and add a new material to the other two not leaves it changes leaves as well
I get the same thing doing that
if they share a material of course they change all three
How are you changing the material
Dragging the material on top of the one I want to change
Dragging a material or a texture
material
I don't want them to
can u show quick vid
This appears to be showing exactly the opposite of what you said was happening
You drag a material onto one of the objects, and that is the object that changes
Yes but what I wanted to do is that all three objects have separate materials
...they do?
Oh I'm just not seeing that on the screen?
The sphere for outside cross changes material but when I drag a material over onto under cross it doesn't change the sphere
!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.
Outside cross has the Outside Cross material.
Then you click on Under Cross and it has the Under Cross Material
So what are you expecting to happen
OK so this sphere is just not changing I don't know why
They are changing
you can literally see them changing in the video you sent
I don't know what you're talking about
Yes but the sphere on the left is not visually changing
Which sphere is that one
leaves
Are you sure, because in your video it changes when you change the material on under cross
Sorry, outside cross
Complete noob to C# here.
Is there a reason when creating my variable '''cs Public bool birdIsAlive = true''' it dsoen't actually set the boolean to true?
Maybe I'm just stupid it doesn't actually do this I want it to have the 3 differnt images on them but when I click leaves it still has outside cross on the left sphere and then when I click click outside crossing as outside cross on the left sphere then when I click under cross it has outside cross on it
It sets that variables default value to true. If you change it in the inspector, that's what value it is
you have a syntax error
Right now, the thing you are saying that you want to be happening but isn't happening is very clearly actually happening in your video
The stuff you're saying isn't happening is happening just fine
Three spheres, all with their own materials. Changing one has no affect on the other two
the one you can see in the scene view is visibly updating when you change its material
I don't know what to tell you. You appear to be hallucinating problems, because your video shows it working exactly as you said you want it to
OK I guess the sphere on the left will not show me each one separately when I click them
How do I make an object show and not show?
toggle the renderer.enabled
okay thanks
Hey. What way to get files inside of the Editor script without serialization would you recommend me? Putting suitable files into the Assets/Resources folder?
what do you mean by "get files"? What are you trying to accomplish
Retrieve a texture inside of the custom Editor
Hi,
I do a prescene to add all objects will be DontDestroyOnLoad with this script :
using UnityEngine;
using UnityEngine.SceneManagement;
public class DontDestroyOnLoad : MonoBehaviour
{
public GameObject[] objects;
private void Awake()
{
foreach (var element in objects)
{
DontDestroyOnLoad(element);
}
}
private void Start()
{
Debug.Log("DDOL activated");
SceneManager.LoadScene("Scene01");
}
}
But when I press play, I'm in the scene01 but my objects in DDOL are desactivated. Why ?
what's wrong with serialization?
Aside from serializing it, your options are Resources, Addressables, or directly reading the file with UnityWebRequestTexture
Some other script must be doing it
It is a canvas not a gameobject it cant take a renderer is there a differnet thing I need to do
I don't want to serialize a texture, which is used for the editor buttons
Alright, Resources should be fine then. Thank you!
if I get an error saying object reference not set to instance of an object, that just means the object I'm attempting to reference isn't being understood right?
Making an object a DDOL won't affect whether it is enabled or not. If something else has deactivated them, then this script will make them deactivated DDOLs
It means something on that line is null but you're trying to do stuff to it anyway
It means it's null
no it means your reference is not pointing to an object
oh ok
you can use gameObject.SetActive
If you have a variable like:
GameObject example;```
`example` is what's known as a "reference". It _refers_ to a GameObject It's like a piece of paper that can have the address to a house on it. But if you leave the piece of paper blank, you can't find a house with it. Null references are like blank pieces of paper without addresses written on them.
I fixewd it
for some reason it un-added my object from the script
so it left the referenced script as null instead of as what it should of been
should of looked more closely mb
I don't have something that desactivate us, that's the problem 😭
I have just this in the prescene
Sorry, as mentioned complete novice, just trying to understand why it works this way.
I see the variable in the inspector and can check or uncheck the box,. But when I first made the script for the first time and set the value to = true, it didn't until I added //myBool = true inside of the Start() function.
Like all my other variables (int/float/str) show the default value I set when they were created before changing them elsewhere in the script or in the inspector. But boolean seems to always start as false unless I set it to true in the start() or update() functions. Is that just a quirk of C#?
sure in the prescene, what about in one of those scripts on those objects? What about in the newly loaded scene?
It could be anywhere
Wait also are those prefabs?
Yes
The inspector always takes precedence over an initializer. Otherwise there would be a lot of issues. The inspector taking precedence is the DESIRED behaviour. Start happens AFTER that though
I'm surprised it's even letting you call DDOL on a prefab
We can't put prefab in a DDOL ?
you would need to instantiate them, then call DDOL on the instances
prefabs don't exist in the game world itself
they are just assets
if you want them in the game world you need to Instantiate them
Gotcha, so false is just how it will always appear in Unity by default, even if the script says otherwise
No
It will do whatever the code says AS LONG AS the inspector is not overriding it
If you add the script to a different game object, you should see it reflect the value you've specified in the field initializer. That's the only time at which the value in the initializer matters.
Yes, it was the issue
Thanks !
If you set it to true in the code and do not ever touch it in the inspector, it will be true
But the second you touch it in unity, it will only use that
Or it could be private and not even show in the inspector, then it will ALWAYS just do what the code says
Thats what i'm saying though, when set it to true and hadn't touched the inspector it was still false.
Add your script to a new game object. What's the value then?
You touched it then.
You may have done so accidentally or forgotten
Why does this not work?
if (Input.GetKeyUp(KeyCode.V)) { isShopShown = !isShopShown; }
if (isShopShown == false)
{
ShopCanvas.SetActive(false);
}
if (ShopCanvas == true)
{
ShopCanvas.SetActive(true);
}
if (ShopCanvas == true) ?
why not just ShopCanvas.SetActive(isShopShown);?
pay attention
Guess so. Don't recall ever doing so, but yeah when I attatched the script to a new game object it showed up as true.
way too advanced
I just did what thought made sense im brand new
not brand new but a few weeks
Why does this not work
if(Input.GetKeyUp(KeyCode.Escape))
{
ShopCanvas.SetActive(isShopShown);
isShopShown = !isShopShown;
}
wrong way round
Still doesnt work it works when I manualy activate the Shop then it will unactive then it wont go back to being active
is this code on ShopCanvas?
yes
So when it's disabled, how do you expect this code to run
code does not run when an object is de activated
As this is on a Canvas which does not have a renderer you might be better going and toggling the Canvas.enabled component/property
Why would it be better?
because your code, as written would work
also activate/deactivate a gameobject is much more expensive than enabling/disabling a component
It works but the only thing is that it will just proformance not as good?
that's not the only thing but it is the most important
Im not too worried becuase im just making a small project to learn the basics
but it never hurts to learn best practices. In game dev always endeavour to do the least amount of changes to achieve the effect you want
100% agree I should be doing that and that sounds right wanan save time
Does anyone know how to make my game less pixelated
make sure your game view is not zoomed in
scale is on the least it can be
beyond that, turn on anti-aliasing.
Where is that
wdym by "least it can be". Is it set to 1?
yeah 1.3x
depends on which render pipeline you're using
What is the aspect ratio set to?
Also, this is not really a code question
better in unity talk, yes?
Heyo can anyone in here help me with an issue im having in unity?:)
Im trying to reference a class in another script, but for some reason i cant figure out why it wont let me
Im very new so im unsure.
Im trying to use Addresource in the shopbutton script
Idk if i've given enough context
so it looks like u made a singleton from ur ResourceManager called instance
ResourceManager.instance would be how u access it
like u have there in ur ShopButton
What do you mean by "it won't let me"?
what happens when you try?

In the other script where i wrote the same thing it turned green, but i am getting this error
That has nothing to do with your question
ohh thats b/c Button is in the UI namespace i beliieve
you're just mssing using UnityEngine.UI;
using UnityEngine.UI;
Now i get this one
You misspelled the function name
look at your screenshot
I see now
Also the fact that your code editor is not highltighting these in red and not autocorrecting means your IDE is not configured properly
errors are king
you should stop what you're doingn and get it configured
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
powpow
the following code is supposed to ensure on that on powerup pickup, the gameobject that's selected to be added to inventory isn't already there. inventory is an array of 3 (0,1,2) called Bullets. any ideas on why this won't work?
public GameObject RandomRoll()
{
List<GameObject> possibleBullets = new List<GameObject> {BouncingBullet, DoubleDMGBullet, PassThroughBullet};
foreach (GameObject bullet in Bullets)
{
possibleBullets.Remove(bullet);
}
if (possibleBullets.Count > 0)
{
int roll = Random.Range(0, possibleBullets.Count);
return possibleBullets[roll];
}
return NoBullet;
}
Did you debug anything related to this? Like which if statements are happening
doesn't seem like any of them are happening?
if you're using visual studio you should use the debugger, the big green button on top
check the value of possibleBullets
i'll try that.
can you. explain what you mean by "won't work"? What's happening instead of the desired behvior?
it doesn't seem to sort anything, just picks a random bullet.
the bullets arent being removed
my theory is that the variable in a foreach loop isnt the same as in a for loop
could you replace foreach with for loop instead?
i'll give that a shot
I don't see any code that would sort anything
your code just picks a random bullet
No sorting here:
if (possibleBullets.Count > 0)
{
int roll = Random.Range(0, possibleBullets.Count);
return possibleBullets[roll];
}```
more of filtering out stuff
?? it makes a list of possible bullets, and is supposed to pick from that. possible bullets shouldn't include bullets that are already in the inventory
What is in Bullets when this code runs
so what is it doing instead?
it's picking one that's already in the inventory?
almost certainly possibleBullets is being populated with prefabs not instantiated gameobjects
I mean - wouldn't prefabs make sense here?
hold on a moment guys, i have an idea. let me try it quickly
and yes, it is prefabs
no prefab != gameObject
Unless Bullets is containing instantiated objects
prefabs are definitely GameObjects, but yeah we have no idea how Bullets is populated. This question is devoid of a lot of context
including what is actually going wrong/happening
note. I spelt gameObject with a small g
how do i actually move an object with transform and a Vector2
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using JetBrains.Annotations;
using UnityEditor.Callbacks;
using UnityEngine;
public class Movement : MonoBehaviour
{
// Start is called before the first frame update
public GameObject Planet1;
public GameObject Planet2;
public Rigidbody2D rb1;
public Rigidbody2D rb2;
public static float initialveloctity;
public Vector2 velocity = new Vector2(0, 0);
public Vector2 initial = new Vector2(0, 8);
public Vector2 acceleration;
public Vector2 force;
public Vector2 displacement;
public float displacementMagnitude;
public float GravitationalConstant = 0.05f;
public Vector2 position = new Vector2(0, 0);
void Start()
{
Vector2 position = new Vector2(Planet1.transform.position.x, Planet1.transform.position.y);
}
// Update is called once per frame
void Update()
{
displacement = Planet1.transform.position - Planet2.transform.position;
displacementMagnitude = displacement.magnitude;
Vector2 velocity = new Vector2(0, 8);
Vector2 force = displacement.normalized*(GravitationalConstant * rb1.mass * rb2.mass) / (displacement * displacement);
Vector2 acceleration = force/rb1.mass;
velocity += acceleration * Time.deltaTime;
}
}
everything i try throws an error
well, whats the error
well, what error? i'd start with that . . .
bcuz there are tons of tutorials for this . . .
cs1612 cannot modify as it is not a variable of the gameobject
post the actual error message. that doesn't tell us enough . . .
we don't know what you're trying to modify . . .
make a new vector
you need to assign the entire position . . .
Technically you can do this(I mean in a fundamental sense you can change your copy) it just won’t be applied your transform
var newPosition = Planet1.transform.position;
newPosition.x += velocity;
Planet1.transform.position = newPosition;
public Vector2 position = new Vector2(Planet1.transform.position.x, Planet1.transform.position.y);
ive done this
but it meant that my planet1 gameobject needed to be static
then assign that to the transform.position . . .
https://paste.ofcode.org/39FxtaFSUvKEGZMQshJMYKw (weaponShooting script)
okay so i did make a new class inside the WeaponShooting script and referenced that new class in the WeaponShooting class then set the WeaponSO.name\DMG\fireRate to WeaponStats in the SetPOCODataToSOData() method then call that method in update but the pistol still does the same dmg as the bow when it last hit so if the bow was charged and dealt like 3 dmg then the pistol does the same dmg as well but it supposed to deal 15 and im not sure on how to fix it
now i have that an object reference is not set to an instance of the gameobject as the static field has just gotten rid of it completely
which i am trying to eliminate by removing all instances of Planet1
you cannot modify a single axis of position because it's a Vector3 (struct) and returns a copy of the position. that's why you need to create a temporary variable, modify that, then assign it back . . .
idk why i did that lmao
no idea what you mean by this. i don't see how assigning the position to a Vector3 gives you a null reference error . . .
You are doing the exact opposite of what was recommended
You are setting the SO data in code at runtime
You set the POCO data to what your SO has.
Again, do not change the SO via code at runtime
You want WeaponStats.name = WeaponSO.name
Anyone here that used a character controller and made a crouching script for it? Im having trouble with mine and would like to take a look at others solutions
its easy to crouch, just scale your player down by an amount you prefer and have a custom movespeed for crouching, you could also make it so you cant jump if you want
i personally dont use character controllers that much but it is what it is, we can help you with your crouch problems if you present code for us
oh my god , im so stupid
and now just let it like this?
I will do that
give me a second to present it fully
for sure 👍
At a quick glance, yeah that looks good.
And no worries. You aren't stupid, this is just part of the process of learning new things. Good work
thank you thank you
also seems like it didnt really fix anything

now getting this error
i donht understand why it sayts my input position on y axis is infinity or undefined
These are the 2 issues (1. The Hitboxes go thru the ground, 2. After the first jump since start the hitboxes start to float/bounce up)
Movement.cs: //Movement code
https://paste.ofcode.org/jhrgUtdq2jLmYyhiRhtkjY
BLUEPRINTS.cs: // Variables (Not all in use)
https://paste.ofcode.org/Jd6sPg6N73n9sEAyE9ZkYC
Thats both when crouching and crawling
Division by zero
yes but ive got displacement.magnitude squared
and there is a difference on x axis
so im not sure why its giving that cause surely the magnitude should just be 22
Either displacement.magnitude is 0, or rb1.mass is zero
let me compare this to my script real quick, ill get back to you in a minute
No worries take ur time
rb1.mass is zero
and i cant console it cause it just wont run
but they are seperated
so there should be a displacement magnitude
When you add NaN to a valid number, that number becomes NaN
im guessing you want your camera to be at the level of which you crouched?
Oh no that i was gonna do after
dont worry about that
currently the hitbox is all over the place (video)
rip , this didnt work 
well im not sure what im adding NaN to
If rb1.mass is zero, then acceleration is NaN
In the second part of the clip after the jump i wasnt jumping whatsoever all it was was pressing the crouch and crawl keys
Then what was this about
Why did you just tell me it's zero
i meant to say it isnt
guys if i use a boxcast to detect if the player is onground, wouldnt that mean that if the player just jumped the exact frame before hitting the ground, they would jump slightly higher? because the boxcast sticks out slightly detecting the player is on the ground JUST before they are?
Can you post the actual !code so it can be copy-pasted and I don't need to retype a whole bunch of stuff?
📃 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.
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using JetBrains.Annotations;
using UnityEditor.Callbacks;
using UnityEngine;
public class Movement : MonoBehaviour
{
// Start is called before the first frame update
public GameObject Planet1;
public GameObject Planet2;
public Rigidbody2D rb1;
public Rigidbody2D rb2;
public static float initialveloctity;
public Vector2 velocity = new Vector2(0, 0);
public Vector2 initial = new Vector2(0, 8);
public Vector2 acceleration;
public Vector2 force;
public Vector2 displacement;
public float displacementMagnitude;
public float GravitationalConstant = 0.05f;
public Vector2 position = new Vector2(0, 0);
void Start()
{
}
// Update is called once per frame
void Update()
{
displacement = Planet1.transform.position - Planet2.transform.position;
displacementMagnitude = displacement.magnitude;
Vector2 velocity = new Vector2(0, 8);
Vector2 force = displacement.normalized*(GravitationalConstant * rb1.mass * rb2.mass) / (displacement.magnitude * displacement.magnitude);
Vector2 acceleration = force/rb1.mass;
velocity += acceleration * Time.deltaTime;
position += velocity;
Planet1.transform.position = new Vector3(position.x, position.y, 0f);
}
}
Pls use one of the links CSD
Make a smaller box
any bigger than that u might wanna use an external paste-bin
so it doesnt take up the whole thing
well yeah but even if the box just stuck out 1 pixel below the player it would still be a problem just to a way way way way smaller degree right? (bro i said frame instead of pixel am i high wtf)
try commenting out the controller.center code, im guessing your setting that to make sure you dont float in the air for a second before you fall to the ground?
will do didnt read
Make it so it doesnt detect the ground if the impact gives damage
should solve it
or atleast that u cant jump
like a temporary stun
void Update()
{
displacement = Planet1.transform.position - Planet2.transform.position;
displacementMagnitude = displacement.magnitude;
Debug.Log($"DisplacementMagnitude: {displacementMagnitude}");
Vector2 force = displacement.normalized*(GravitationalConstant * rb1.mass * rb2.mass) / (displacement.magnitude * displacement.magnitude);
Debug.Log($"force: {force}");
Vector2 acceleration = force/rb1.mass;
Debug.Log($"acceleration: {acceleration}");
Vector2 velocity = new Vector2(0, 8);
velocity += acceleration * Time.deltaTime;
position += velocity;
Debug.Log($"position: {position}");
Planet1.transform.position = new Vector3(position.x, position.y, 0f);
}
Replace your function with this one
If your game is so precise that 1 extra pixel of jump height breaks it, you should reconsider
the controller.center makes it so when i crouch/crawl the hitbox moves down instead of floating
without it the smaller hitbox simply stays in air
instead i would recomend applying a force down for a second to eradicate this issue
How do I make calculations in a script
this is most likely your problem
With math
true
yes long calcualtions
it wouldnt break it, i've just never seen a game with tech where you jump and jump b4 u hit the ground to get slightly higher
plus i like precision i guess
and also i plan to add buffered inputs for obvious reasons which would make it much easier to do yk
You almost certainly have, you have just never noticed
if you are worried about a pixel difference couldn't you just apply a tiny force down for a second to negate it?
good point
Nvm it did work but only after the first jump for some reason and also when i crouch/crawl i fall from the standing position
a lerp will fix that
so i dont find that as an issue
but the jumping part is one
the more i look around , the more i get my suspicion that it might be because of the enemy on collision code but not sure
You would... do the calcualtions. In script. You can write math operations in C#.
can someone please explain in an almost annoying amount of detail, why everthing in this line works/what it does?
rb.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse);
That's the least vague answer I can give with how vague the question is
Nvm got it solved now
the controller skin was stuck in the ground
solution was to make the character drop a little bit on the ground
vector2() is X and Z right? not X and Y?
oh and this can obviously be assumed but rb is created by this line in start
rb = GetComponent<Rigidbody2D>();
No
correct me if im wrong
thanks
I can explain the first bit, i dont know what the second bit does tho.
AddForce simply pushes it with a force in the direction of the Vector and the Vector is created in that line and set to 0 X and jumpForce amount to Y pushing it straight up with that force.
z would be the depth and if its easier to remember it just goes in alphabetal order so x y z
in future consult the docs for such simple questions
forcemode.impulse applies the force once i believe
im demotivated because i feel im not learning and unity learn is slow
will do
how long has it been
Longer than the 10 minute Youtube meme video that made it look so easy at the very least
a week and 2 days
game dev and Unity is a very complicated thing to learn, it takes years not days or hours
been working 5h a day
during a crouch w/ a CC i usually change my (center and my height)
starting height starts at 2, center is 1, so when i crouch it turns to 1, and .5 .. I use Mathf.MoveTowards for smoothing.. (my hitbox then matches my character pretty easily)
in this race, you're the tortoise, not the hare . . .
so rb.AddForce is just a thing that moves something with the physics engine specifically, then makes a vector to determine how/where it moves
so this is obv just for my jumping but should i be using this for my movement too? rn im using just like transform.position += Vector3.right * speed *Time.deltaTime
and yeah i still have no clue what forcemode2d.impulse means (time to google it/ask chatgpt)
Then you're about 207 weeks shy of the usual amount of time people spend learning
not sure if its a question u had.. or I caught the end of something
how do i learn faster
so if it wasnt for that it would just continuously move that way?
i hate watching 1h of videos
you dont
Learning programming is a rollercoaster and a slow burn to learn. It takes a long time but as you go on it gets satisfying and it has its ups and downs of burnout where you need to take a small break before heading back into it
dont worry
correct
its a part of the process
not exists
it would default to forcemode.force
that's like one week of class. how much did you expect to learn in such a short amount of time? a semester is, at least, 3 months . . .
i'm closing in 4,160 hrs
i understand it takes a while but im not as motivated as i was a week ago
watch the GMTK flappy bird tutorial, follow along, then once you're done get an idea for something else to add, and research how to add it (chatgpt or google or whatever), then when u have code that works, learn WHY it works
Yes vectors3 should be used for movement but you could also add the jumpforce into the same vector which you have movement in to make it more compact even tho it isnt necessary
what is a diffrent way i can learn other then videos
i am more motivated when i see something i make working..
i tend to jump around projects.. just to make something
then i have my main project that i go back and forth too..
(the tedious one)
Motivation is a fickle bastard who can't be depended on for anything. Discipline is how you actually get things done
💯 couldnta said it better myself
with several attemps and many fails and a lot of help from here i got most of my movement code done, so it does take time to get better
i want to make something myself without a tut but i feel i dont know enough
you cant really expect to learn something from a 10 min "how to easily make games in unity" video , it takes lots of practice and time to learn and get to where a expert unity developer is but the experience is painful but fun to learn , you just kinda need problem solving skills and a bit of determination and you should be able to atleast get to a beginner level , for a expert level you have to practice more and more yk
Personally i used a 4 hour course and after that i dropped the training wheels and started doing trial and errors, ran into multiple walls but kept going cause its satisfying once the code works
videos, github repos, reading articles, doing game-jams, downloading sample projects.. (reverse engineering them)
Then go do things
to be honest, you don't need motivation: you need discipline and consistency. people are only motivated to do the things they want to do when they want to. never rely on motivation because it depends on your personal (internal) state of mind . . .
They don't need to do well
but just do things
Learn how to solve problems that come up because that's all programming is
do things frequently... do things well sparingly.. 😄
a series of encountering a problem and then finding out how to solve it
i usually punish myself to combine some code like my weapon shooting code with a cool chargeable bow code and i did it , works good , just have to fix the Dmg , its a really fun experience and feels good seeing it work
100 percent.. "omg it works" moments push me forward
coming from a 2d dev to a 3d dev its hard to come up with ideas
like i said, what a short tutorial to understand VERY fundamentals, like the gmtk flappy bird one, then just make stuff with google and stuff
also if everything is still to confusing, try learning something like python first, cuz python is bassically just english but weirder, and it teaches concepts of programming in a very accessible way so you dont have to worry about where to put punctuation ect
i alwasy think that programming is more about problem solving skills icl
different eggs, same basket
Programming is just "Googling, with purpose"
i dont agree w/ the learning python to learn unity bit
Speaking as the old, wise man, motivation comes from enjoyment, the more you enjoy game dev the more motivated you will be
this is true
Literally like 5 mins ago when i got the issues solved i jumped out of my chair and screamed lets go so loud my mom told me to shush
lmao
i dont mean to learn unity, but just if programming concepts are too confusing yk
haha feels good dunnit
python to me is more confusing.. b/c its soo relaxed of a language..
hi! i´ve been runing into a problem, i want to make a triple shot, but i dont know how to offset the other 2 bullets, i have tried everything from; multiplying vectors and quaternions, using radians, degrees, etc, pretty sure one of them would work but i dont think im writting the code i need correctly
Make your 2d games 3d its a fun expierience
make old btd games into 3d
If you use Python to learn programming you will betray yourself and never really understand it. The best way to learn programming is via C, second best is Java/C#
i just mean for learning the core concepts of programming
learning what a variable is is much easier when its "hoursinaday = 24" not "private const int hoursinaday = 24;"
C plus plus, i guess i cant say c plus plus without getting flagged
The fundamentals of programming don't get easier when you do them in a different language. Logic, control flow, and compartmentalization are language-agnostic, as long as you're not literally fighting the language it doesn't matter
I would change the rotation of them slightly from point of where they shoot out
If you must, that works too. The important bit is that it has no training wheels.
i have a book for it, its fun
oh yea, thats always useful. im just hating on Python ;D.. i built a discord bot once.. never ever will i willingly work on python again 😄
How are you getting the direction of the first line?
but hard
!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.
anyone can help me with this? the dmg of the chargeable bow is being set to the pistol dmg as well and i dont want that 
sorry, but that is complete crap. Concepts are concepts the language is irrelevant
You can only ever learn coding once. If you learn it through C you get the best start.
i dont know how to rotate the vector to be pointing towards the objective
learning C just to get into c# is not really worth the trouble
For me coding was simply translating thoughts into something my pc could read
That doesn't answer the question, direction is not defined here
i didn't want to start a python flame war.. just wanted to point out imo that learning python before isn't really necessary.. (my dislike of python ofc influencing my opinion) 😄
not necessarily, you dont need to learn C or C++ or python to get the best start.
thats what it is.. (a list of instructions)
i think python is good for teaching extreme basics of how programming works, conceptually
not how to write code
like i said, python is bassically just english with extra steps, most python scrips when read out loud can be vaguely understood, which makes it very accessible and comprehendible so while it would be more worth your time to learn a more complex language first, if its too hard python could work
recreate very simple games. challenge yourself to replicate their mechanics and gameplay, then add your own systems/mechanics on top of their game. that will show you can create games by following a provided documentation (the replication) and expand on those ideas by implementing new mechanics (your creativity/expression)
there are simple "clone" games we usually provide: flappy bird, asteroids, galaga, brick breaker, single 2d-mario level, 2d/3d infinite runner . . .
direction is defined in other update but its basically objective.transform.position - transform.position
No. That is the fundamental mistake.
ya, i see what ur saying.. to each their own.. if it helped you thats fantastic..
Python is only used in academia for learning because there they don’t care about actually running code in real hardware.
only the pros code with linux command line
results may vary imo
facts
Okay, and do you want the other two shots to be offset randomly, by a certain distance, or by a certain degree
i think any language is good as almost all languages rely on the same things just worded differently
i want them to be offset for an exact amount of degrees
when u get down to the nitty gritty, yea, they're all pretty similar
as in the image, one towards the objective, and 2 others to the sides
sorry for being annoying but ive been stuck on this problem for hours 😭
no worries.. can u share ur code.. !code in a pastebin website.. or something other than a screenshot..
📃 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.
Every programming language is just "English with extra steps" and can be read aloud. In fact, Python having things like significant whitespace and lack of strong typing actually make it a uniquely bad language to start learning with. It hides a lot of the boiler plate, but you still need to understand that boilerplate
and briefly explain ur issue once more
i would create an empty to track the orientation of the first arrow then offset the other 2 from that orientation
an empty? what is that?
i hate pythons whitespace.. that is all 😄
can we see full code then?
w/o a good ide formatting for me.. my python would be a mess
Its a little thingy that holds transforms, rotation etc
https://paste.ofcode.org/3Ywv2vcLLX3TmSMTYtAJ4J (WeaponShooting script)
thank you 👍 now whats not working?
yeah just sent it now , mbmb
you need to rotate the direction based on an angle before passing it to the instantiated bullet . . .
where are your scripts?
just a gameObject w/o any other components attached except its basic Transform component
if you make its absolute 0 the same as from where the arrows fly out of you could make it as i said
oh, i see, i see . . .
i will say python is atleast very good for someone who wants go code casually, cuz you can do SOOO much with it and its so hilariously easy to learn
how do i rotate the direction based on the angle that i need?
if u never seen code in ur life.. and want to learn code.. yea python is a go-to
but in context of unity.. i dont see its relevancy
the only reason why i dont like python is because its way to expensive than it has to be
but its very easy to learn
well, now i know who the python fan bois are 😈 lol j/k j/k
so i have a chargeable bow and based on how long you charged it increases the dmg and the 35 is the max , but for some reason when i deal dmg to an enemy with the bow and then go and buy the pistol , for some reason the pistol dmg is the same as the the last bow dmg it dealt so if the player charged the bow and dealt like 3 dmg to an enemy then the next time i damage enemies with the pistol it deals 3 dmg and not 15 as its sent in the inspector so im not sure on how to fix it
i have tried multiplying a quaternion with the direction vector, but it didnt go well, probably because i wrote it wrong
So, you have direction, and you want two more angles offset by the same amount in either direction?
Take advantage of the fact that a quaternion multiplied by a vector applies that rotation to the vector:
direction;
Quaternion.Euler(0, 30, 0) * direction;
Quaternion.Euler(0, -30, 0) * direction;
where is your buy script and pistol script?
so ur using the same damage amount variable for all weapons?
or this
those things should not affect eachother
let me look at the script right quick #💻┃code-beginner message
It is exactly as "hilariously easy to learn" as basically any imperative programming language
why do all people use the one on the middle, shouldnt it be the in the z? or since its a quaternion it takes other numbers
yeah ik but for some reason they do
because i have exactly that but in the "fake z axis"
How can i change one value to another smoothly and consistently, the 3 courses i looked into explained it confusingly
Well, it'd be whichever angle you want to rotate about. We aren't sure the orientation.
yeah but the weapons are diff prefabs so i jsut set how much dmg they deal on the prefab and on the SO as well
i think conceptually, yes, but learning to actually WRITE it i think python is way easier
I use Mathf.MoveTowards()
unity used weird vectors unity uses Y as up
brb
okay so if i want ot rotate it on the z axis since its 2d
Ill look into that thankyou
Y is not 'weird' it's a standard
Yeah, then you'd use the Z axis
i need to write it in the z ?
i only have WeaponShooting script that handles all the shooting n stuff of the weapon
bulletHolder.transform.rotation = Quaternion.Euler(0,0,direction.z-30+ (30*i));
theres mathf for floats and Vector3 for.. well... Vector3s ofc
It's not standard, but it's not weird either.
Its a standard
You see how you're currently using direction to point the bulletHolder?
yes
https://gdl.space/ifonodavan.csalso the ShopManager script that handles the buy stuff
The weird one is unreal lol
Perfect and what parameters do i enter and what does each one do
I have a bit of a problem with a function I made which is supposed to make the character look towards the mouse cursor in 3D space
private void GetMousePosition()
{
Ray ray = mainCamera.ScreenPointToRay((Input.mousePosition));
if (Physics.Raycast(ray, out RaycastHit raycastHit, float.MaxValue, groundMask))
{
Vector3 direcion = Camera.main.ScreenToWorldPoint(Input.mousePosition - transform.position);
transform.forward = direcion;
direcion.y = 0;
transform.position = raycastHit.point;
}
}
```
My problem is the character attaches itself to the mouse cursor along the layermask and I'm not sure what's wrong
You want to do that with all three of the directions I sent here:
#💻┃code-beginner message
sorry for the trouble.. but can u use a different one? !code paste.ofcode.org maybe
📃 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.
There are many standards
ur link is dead
the site is dead lol
ooof lol
Use your debugger to track the damage variable
^ debug the value when u set it.. when u change it.. before you use it
https://gdl.space/ozoferimoq.cs heres the WeaponShooting script
find when it doesn't work the way it should
when you know where its going bad.. its easy to fix
it works!
who else likes this font
i made it work somehow https://gdl.space/uceguqibot.cs
when you switch weapons.. the damage value isnt being reset properly
so the previous value from the bow is used
ooh , how can i reset it then?
though, i'm not feeling the all lowercase class. turn that into PascalCase and we good . . .
By setting it to the damage value you want
you need to reset the value whenever you switch weapons.. looks like u can do that in ur SetPOCODatatoSOData
cant i do it here?
private void SetPOCODataToSOData()
{
weaponStats.name = weaponSO.name;
weaponStats.fireRate = weaponSO.fireRate;
if (weaponSO.name != "Bow")
{
weaponStats.Damage = weaponSO.DMG;
weaponStats.BeforeDamage = weaponSO.BeforeDMG;
BowCharge = 0f; //reset bow damage
}
}```
back
if current weapon is not bw.. the method sets the weaponStats.Damage and weaponStats.BeforeDamage to values in the SO
then it sets bowcharge to 0 to ensure that any residual charge from the bow is cleared out
Oh what parameters do i put in and what do they do?
You can set weapon stats when equipping
Anyone able to help with this?
https://docs.unity3d.com/ScriptReference/Mathf.MoveTowards.html
This function is similar Mathf.Lerp except that this function ensures the rate of change never exceeds maxDelta and that the current value is never greater than the target value. Negative values of maxDelta pushes the value away from target.
Send the !code again formatted
📃 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.
whats maxdistancedelta?
private void GetMousePosition()
{
Ray ray = mainCamera.ScreenPointToRay((Input.mousePosition));
if (Physics.Raycast(ray, out RaycastHit raycastHit, float.MaxValue, groundMask))
{
Vector3 direcion = Camera.main.ScreenToWorldPoint(Input.mousePosition - transform.position);
transform.forward = direcion;
direcion.y = 0;
transform.position = raycastHit.point;
}
}
I thought it was to begin with
i use 7 * Time.deltaTime otherwise known as Seven Seconds
this didnt work 
Oh so its the time it takes?
oof, well regardless.. the issue is u need to reset ur damage for w/e gun ur using..
it isn't being done atm
basically
* 7 per second
Not formatted and not on a paste site
why is this not making xpos into a var that i can transform to
yes..
perfect
transform.position isnt a float
Because a float isn't a vector
transform.position = new Vector3(xpos, transform.position.y, transform.position.z);
what does the error say???
that is formatted?
Well for one, in that second image, there's no such thing as xpos
Pretty strange that discord isn't formatting that
https://gdl.space/umokizumot.cs
anyway here it is on a pastebin
private void GetMousePosition()
{
Ray ray = mainCamera.ScreenPointToRay((Input.mousePosition));
if (Physics.Raycast(ray, out RaycastHit raycastHit, float.MaxValue, groundMask))
{
Vector3 direcion = Camera.main.ScreenToWorldPoint(Input.mousePosition - transform.position);
transform.forward = direcion;
direcion.y = 0;
transform.position = raycastHit.point;
}
}``` real formatting
The difference being keywords and data type have a colour change?
the dmg for the pistol doesnt get changed at all not even in the pistol SO , it remains 15 so im unsure on why this happens
i mean, thats all i noticed 😄 all i did was add cs to the codeblock..
but regardless ur paste-bin resource is much better 👍
i only want x pos
atleast u didnt send a screenshot.. or even worse.. a cell pic of ur monitor 😄
that only sets the X
it keeps the same Y and same Z of what transform.position already is
you can't directly set 1 property of the transform.position like that
Looks readable to me
lmao (╯°□°)╯︵ ┻━┻
Vector3 newPosition;
newPosition = transform.position;
newPosition.x = xPos;
transform.position = newPosition;``` would also do the same
slowly losing it icl
take a step back.. reorganize ur thoughts and then return
Anyone able to help with my problemo?
Here's your direction 🙂
How do i make the movetowards faster?
increase speed
Well, theres three parameters to movetowards
It's getting the correct mouse cursor location, the problem is it's translating the character instead of the character direction
and one of them is the maximum amount to move in a frame
hmm i saw smth but not sure if its the problem so when im in the shop tab i can still yk move around and shoot so when i press to buy the pistol , it charges the bow so maybe thats why , what if i freeze the game and then turn canFire off
private void GetMousePosition()
{
if (mainCamera == null)
{
mainCamera = Camera.main;
}
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out RaycastHit raycastHit, float.MaxValue, groundMask))
{
Vector3 direction = (raycastHit.point - transform.position).normalized;
direction.y = 0; // Ignore the y-component to keep the direction on the horizontal plane
transform.forward = direction;
transform.position = raycastHit.point;
}
}``` if its a 3d game i Raycast into the scene using `camera.ScreenPointToRay`
void Start()
{
Debug.Log("Player created");
cc = GetComponent<CharacterController>();
mainCamera = Camera.main;
}
I have it in the start function
Vector3 mouseScreenPosition = Input.mousePosition;
/// <summary>
/// Use Raycast Method for Casting into 3D Environments
/// </summary>
if (useRaycast)
{
Ray ray = Camera.main.ScreenPointToRay(mouseScreenPosition);
if (Physics.Raycast(ray, out RaycastHit hit))
{
Vector3 hitPosition = hit.point;
transform.position = new Vector3(hitPosition.x, hitPosition.y, hitPosition.z + raycastOffset);
if (useNormal)
{
transform.up = hit.normal;
}
}
}``` heres the method pulled from my own Raycast (cursor 3d script)
theres more to that codeblock than just the mainCamera assignment
i got the help of chat gpt because im a loser
Did it tell you literally the exact same things we did
This is still doing the same thing I'm afraid 😦
i didint understand what yall said
works as intended in my project 🤔
debug the raycast hit..
see if it actually raycasts into the scene..
Ah I know what you mean, The mouse location part is fine and was originally. But when I attach it to a character then the character is attached to the cursor also
Debug.Log($"Raycast hit {hit.collider.name}");```
My aim is to get the character to look towards the mouse cursor on a level y-axis
i use LookAt() functions for that..
and pass in the same Y value as the object's
LookAt(new Vector3(theRaycastHit.position.x, transform.position.y, theRaycastHit.position.z)); something similar to this ☝️
regardless of what method u use.. the same idea can be applied.. (that.x, yourown.y, that.z)
okay i fixed the dmg n stuff but now im trying to check if in the shop area then if you hold E down then you will open the shop etc but im not sure how to do it , i tried it onColliderEnter2D and OnTriggerEnter2D but nth tbh
Nevermind, I think I've done it 🙂
Those would only work if you pressed e at the exact time the collidor was entered. Just raycast I think?
Thank you very much for the help @rocky canyon 🙂
Or just check the distance between user and shop and if it's in range it opens
There's prob a better solution though I'm no expert
Or OnTriggerStay2D()
tried it , doesnt work
very welcome 👍
I have a new problem now and that's because the smooth camera follow is conflicting with it now haha
I know exactly where to look, I just need to figure out why it's conflicting now 🙂
Sprinkle some Debug.Log()s around - find out what isn't working.
Two potential problems:
- I can't remember if physics gets paused when
timeScaleis0f- if it does, it would prevent you from closing the shop thingy - Checking for single-frame input events in a physics-relevant message like
OnTrigger*may fail on occasion as their values are updated per frame, but the message will execute per fixed-step.
private void OnTriggerStay2D(Collider2D other)
{
if (other.CompareTag("Player") && Input.GetKeyDown(KeyCode.E))
{
Interact();
}
}
private void Interact()
{
Debug.Log("Interacted with E");
}``` OnStay Method
```cs
private bool canInteract = false;
private void Update()
{
if (canInteract && Input.GetKeyDown(KeyCode.E))
{
Interact();
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
canInteract = true;
}
}
private void OnTriggerExit2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
canInteract = false;
}
}
private void Interact()
{
Debug.Log("Interacted with E");
}
``` Extra Boolean Method
i do something similar w/ Button's b/c theres no Stay() for buttons
button clicker bb!
isHovering
if theres a better method.. i'll wander up on it sometime
One other issue here is checking for key down then key up. If you tap a key, both of these events will occur in very short order - so all other things aside, this would only keep the shop open while you're holding down E
How can i change the position of my camera? When i write Camera.position.y it says its not a variable and i cant change it
thank youu
Are you using Camera as in Type or do you have a variable with that name?
u can't directly change the transform.position's individual properties..
you need to copy out the variable change it and reapply it
thats not what the error is . See linked page #💻┃code-beginner message
Vector3 newPos;
newPos = camera.transform.position;
newPos.x = newXValue;
camera.transform.position = newPos;``` something something
yes best they read the explanation though, if we feed them they wont know why they had to do it in the first place
i still dont know why i have to do it 😄
goes to read
Materials really messed me up..
the bottom part explains it a bit more in detail
seems like inputs dont work when the timescale is 0
Material newMaterial = new Material(renderer.material);
newMaterial.mainTexture = newTexture;
renderer.material = newMaterial;```
cliffnotes
Position is simply returning a copy Transform.position
yea, the update loops stop
you can't modify a copy it makes the whole thing useless
