Access violation when changing component's variable

I have a gun setup as a custom component, with a float variable to keep track of when to shoot. I set it to 0.0f in the component’s constuctor (and even tried in BeginPlay() instead). Then, the only other place it’s used is in the component’s firing method.

// The firing function
39.    void UBaseGunComponent::Fire(float DeltaTime)
40.    {
41.    	if (fireTimer == 0.0f)
42.    	{
43.    		// ToDo - Shoot
44.    	}
45.    	else if(fireTimer >= 1000 / rateOfFire)
46.    	{
47.    		fireTimer = 0.0f;
48.    	}
49.    	
50.    	fireTimer += DeltaTime;
51.    }

When I try to set fireTimer to a new value in the method, the engine crashes and throws up an access violation error. The error reporter says that the violation occurred at line 40, but if I comment out the assignments to fireTimer, it doesn’t crash which is why I think it has something to do with the variable assignments.

The Fire() method is called from the parent actor’s Tick() method.

Access Violation happens on Pointers that are not Valid. I assume your fireTimer and rateOfFire are not float* right? So nothing wrong there.

However your Component is a Pointer. Make sure its valid before you try to Call any Function on it.

if(myGunComp != nullptr)
{
myGunComp->Fire(DeltaTime);
}

Make sure you created your Component properly and its not Garbage Collected. Most UE4 Cpp Tutorials cover this or its easy to google up so I won´t explain this Part.

Thanks. I’m still not very well versed with C++, especially pointers. I thought that the component was initializing fine since removing the assignment statements kept it from crashes. The problem was what you suggested, combined with the blueprinted version of the player’s class nulling out the gun component.

Adding that null check and remaking the blueprint fixed it.